Java

TOPIC 19 – JAVA COLLECTIONS I - LISTS

 

 

LESSON NOTE 2

 

 

LIST

 

We will look at two implementations of the List interface.  The classes we will look at are ArrayList and LinkedList.

 

Both provide the user with the same functionality because they are both Lists.

 

ARRAYLIST & LINKEDLIST METHODS

 

Here is a listing of the most useful methods for lists:

 

  • add – adds an element to the end of the list
  • addAll – adds all elements of another Collection to the list
  • clear – removes all elements from list
  • get – returns a reference to the specified element
  • remove – removes an element from the the list
  • size – returns the number of elements in the list
  • toString – returns a string version of the content of the list

 

Of course, using an IDE like Eclipse makes using a new Class so easy because you can see all the method options that you have.

 

IMPLEMENTATION DIFFERENCES

 

An ArrayList object provides all List functionality to the data that is actually stored in an array.  It is very efficient at looking up the content of a specific index.  It is inefficient when adding or removing elements because arrays are static sizes and resizing involves copying all existing data over into a larger/smaller array.

 

A LinkedList object provides all List functionality to the data that is stored as a chain of individual nodes that reference the next element in the chain.  It is very efficient as adding and removing elements (if used correctly).  However, it is inefficient at looking up specific elements located at a specific index.  Note that we will take a closer look at LinkedLists later.

 

     ArrayList<Integer> al = new ArrayList<Integer>();

     al.add(5);

     al.add(8);

     al.add(11);

     System.out.println(al);

     al.add(1,9);

     System.out.println(al);

     al.remove(0);

     System.out.println(al);

     al.clear();

     System.out.println(al);

     al.add(2);

     al.add(5);

     System.out.println(al);

     al.set(1, 22);

     System.out.println(al);

     System.out.println(al.contains(21));

     System.out.println(al.contains(22));

          

     for(int i=0; i<al.size(); i++)

     {

           int tmp = al.get(i);

           System.out.println(tmp);  

     }

[5, 8, 11]

[5, 9, 8, 11]

[9, 8, 11]

[]

[2, 5]

[2, 22]

false

true

2

22