Home > Blockchain >  How can I save only some elements of a List in an ArrayList?
How can I save only some elements of a List in an ArrayList?

Time:04-16

I tried to do this, but the add in the line arrayList.add give me an error

    List <Recipes.Results> list;
    ArrayList <Recipes.Results> arrayList;
    

    arrayList = new ArrayList<Recipes.Results>();

    for (Recipes.Results re: list){
        arrayList.add(re.getId(), re.getTitle(), re.getImage());
    }

Im trying to create an arraylist whit only 3 elements of the List, that it contains 5. Example, the List contain a class Results whit id, image, title, nutrients, typeimage. I want only to pass id,image and title to the arraylist. How can I do that?

CodePudding user response:

The add method requires a Recipes.Results object as a parameter. You are passing in a set of member variables instead. Before the call to the add method, put in some condition or processing to determine what object to add to the ArrayList. You mat need to define a new class that is similar to Recipes.Results that contains just a subset of the data, or you may wish to construct new Recipes.Results objects that contain 1 or more null fields.

CodePudding user response:

ArrayList.add(x) -> Add x to the end of the ArrayList.
ArrayList.add(y, x) -> Adds x to the position y in the ArrayList

These are the main ways to use ArrayList. There's no 3 parameter ArrayList.add()

  • Related