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.
intparametermyInts(plural)? Anintis singular and not aCollectiontype or array. This is confusing an prevents me understanding your problem.nullto both examples and then trying to do something with theArrayListfield? With the first one it would throw an exception.myIntsarg to the constructor was also supposed to be anArrayList<Integer>, not anint, am I right?