Java List Part I

Java list<> is a collection stores elements by insertion order (either at the end or at a specific position in the list). A list maintains indices of its elements so it allows adding, retrieving, modifying, removing elements by an integer index (zero-based index; the first element is at 0-index, the second at 1-index, the third at 2-index, and so on).

A list can store objects of any types. Primitive types are automatically converted to corresponding wrapper types, e.g. integer numbers are converted to Integer objects. It allows null and duplicate elements, and orders them by their insertion order (index).

 

The List is the base interface for all list types, and the ArrayList and LinkedList classes are two common List’s implementations.

 

ArrayList  quick example: 

List<String> listStrings = new ArrayList<String>();
listStrings.add("One");
listStrings.add("Two");
listStrings.add("Three");
listStrings.add("Four");
 
System.out.println(listStrings);

LinkedList quick example: 

List<String> listStrings = new LinkedList<String>();
listStrings.add("Five");
listStrings.add("Six");
listStrings.add("Seven");
listStrings.add("Eight");
 
System.out.println(listStrings);

In Java 7, we can remove the type parameter on the right side as follows:

List<Integer> listNumbers = new ArrayList<>();
List<String> linkedWords = new LinkedList<>();

 

The compiler is able to infer the actual type parameter from the declaration on the left side.
When creating a new ArrayList using the empty constructor, the list is constructed with an initial capacity of ten. If you are sure how many elements will be added to the list, it’s recommended to specify a capacity which is large enough. Let’s say, if we know that a list contains around 1000 elements, declare the list as follows:

List<Integer> listNumbers = new ArrayList<>(1000);
It’s also possible to construct a list that takes elements from an existing collection, for example:

List<Integer> listNumberOne; // existing collection

List<Integer> listNumberTwo = new ArrayList<>(listNumberOne);
The listNumberTwo constructed with copies of all elements from the listNumberOne.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

Up ↑

%d bloggers like this: