For example I can do this with a basic integer array:
int[] test1 = new int[]{2, 1, 5, 1, 3, 2};But with an Array list I have to add them one at a time like this
List<Integer> test1 = new ArrayList<Integer>(); test1.add(2); test1.add(1); test1.add(3);
?
java - Add String Array to ArrayList - Stack Overflow
java - How to add elements of a string array to a string array list? - Stack Overflow
Adding objects to array list - Last entry overwrites all elements
You are only creating one instance of the class Recipe. And you are adding it multiple times to the ArrayList. This will modify the object everytime.
What you need to do instead is to create a new Recipe before setting the name, and then add it to the ArrayList.
More on reddit.comWhy is the list method which returns all but the last element named init?
Just some observations:
-
head,tail,init,lastare all four-character words -
Haskell uses these same operations
-
Erlang also seems to use these terms
-
Okasaki's book/thesis also contains these, language is Standard ML
Scala borrowing from these functional languages (particularly ML and Haskell), my guess is the terminology was inspired from these.
More on reddit.comVideos
You already have built-in method for that: -
List<String> species = Arrays.asList(speciesArr);
NOTE: - You should use List<String> species not ArrayList<String> species.
Arrays.asList returns a different ArrayList -> java.util.Arrays.ArrayList which cannot be typecasted to java.util.ArrayList.
Then you would have to use addAll method, which is not so good. So just use List<String>
NOTE: - The list returned by Arrays.asList is a fixed size list. If you want to add something to the list, you would need to create another list, and use addAll to add elements to it. So, then you would better go with the 2nd way as below: -
String[] arr = new String[1];
arr[0] = "rohit";
List<String> newList = Arrays.asList(arr);
// Will throw `UnsupportedOperationException
// newList.add("jain"); // Can't do this.
ArrayList<String> updatableList = new ArrayList<String>();
updatableList.addAll(newList);
updatableList.add("jain"); // OK this is fine.
System.out.println(newList); // Prints [rohit]
System.out.println(updatableList); //Prints [rohit, jain]
I prefer this,
List<String> temp = Arrays.asList(speciesArr);
species.addAll(temp);
The reason is Arrays.asList() method will create a fixed sized List. So if you directly store it into species then you will not be able to add any more element, still its not read-only. You can surely edit your items. So take it into temporary list.
Alternative for this is,
Collections.addAll(species, speciesArr);
In this case, you can add, edit, remove your items.