I'm currently learning beginner level Java and have a problem with an ArrayList when used in a constructor as a parameter.
When I have to initialize an ArrayList in the class constructor, I usually write something like this (for the sake of this example, let's assume that I want to create an ArrayList of integers as the class field).
public class Example {
private ArrayList<Integer> myList;
public Example(ArrayList<Integer> myInts){
this.myList = myInts;
}
}
However, when I see people do the same thing in tutorials or textbooks, they write the following code:
public class Example {
private ArrayList<Integer> myList;
public Example(int myInts){
this.myList = new ArrayList<>();
addIntegers(myInts);
}
public void addIntegers(int myInts){
this.myList.add(myInts);
}
}
Is there a difference between the two examples? I assume mine is the wrong way to do it, but actually running both versions gives me the same results (to my limited understanding, that is), so I'm struggling to grasp what sets these two variants apart.