I start learning the Java generic collection using Deitel Harvey book – but I am facing a difficulty understanding the three line of codes below – Do all of them perform the same operation on by intializing and adding the relevant values of array ( colors ) to the LinkList variable (list1). How does the second method and third method works – I am having a bit difficulty understanding how Arrays can viewed as a list.. As I know arrays are not dynamic data structure, they have fixed sized length, adding/ removing elements on array can not be done on running time comparing to Lists in general.
String[] colors = { "black", "white", "blue", "cyan" };
List< String > list1 = new LinkedList< String >();
// method 1 of initalizing and adding elments to the list
for (String color : colors)
list1.add(color);
// method 2 of initializing and adding elements to the list
List< String > list1 = new LinkedList< String > (Arrays.asList(colors));
// method 3 of initializing and adding elements to the list
List< String > list1 = Arrays.asList(colors);
Please help me understand my queries above, don’t judge me as I am still new to this.
Thank you, Sinan
Every time you are interested in implementation you can look into certain method. For example, by press Ctrl+left mouse button onto method or class.
This code leads to:
In constructor of
ArrayList:the actual array is copied to encapsulated private array field(link is copied).
Then in constructor of
LinkedList:Every element of passed collection is added to the
LinkedList.