Saturday, December 6, 2014

How to Initialize ArrayLists (not like Array initialization)

Here are two ways to initialize an array:

int [] x = { 1, 2, 3, 5 };

Of course, you can also initialize Arrays manually, like this:

int [] x = new int[4];
x[0]=1;
x[1]=2;
x[2]=3;
x[4]=5;

Now lets look at the comparable ways to initialize an ArrayList of Integers:

Here is the manual way:

ArrayList<Integer>  x = new ArrayList<Integer>();
x.add(1);
x.add(2);
x.add(3);
x.add(5);

If you try to use the {} to initialize an ArrayList, it will not work:

Arraylist<Integer> x = {1, 2, 3, 5}; // this will not compile

The above will not work because this syntax is not supported by java.

Here is the proper way to initialize an ArrayList in a single line of code:

ArrayList<Integer>  x = new ArrayList<>(Arrays.asList(1, 2, 3, 5));

What is happening in the above line of code is that the Arrays class is providing a static method called asList(), which is taking the numbers and converting them to an ArrayList. The variable x is then used to point to the newly created list.
This latter (more sophisticated) method of initializing an ArrayList is NOT tested on the AP exam (or my exams) but is handy. I am showing it to you here because I have used it in your ArrayList Intro Lab and did not want you to get confused by it.

mr. sarkar

No comments:

Post a Comment