List Tutorial Java

List Tutorial Java

List Tutorial Java: It is advised to read List Fundamentals before proceeding the following programs.

Four programs are given on List with different functionalities.

  1. List Methods: Uses frequently used methods like size(), add(), get(), contains(), indexOf(), lastIndexOf(), subList(), remove(), clear() and isEmpty().
  2. List Iteration: Comparing two lists with equals(), converting list elements to array with toArray(), printing array elements with foreach loop, printing list elements with Iterator (forward) and ListIterator (forward and backward).
  3. List Reversing Sorting: Reversing and sorting the list elements with methods asList(), sort(), reverseorder.
  4. List Unique Elements: Removing duplicate elements from list, sorting list elements, converting list to Set and again set to list.

This is the second program on List Tutorial Java and does the following operations on list elements.

  1. Comparing two lists with equals()
  2. Converting list elements to array with toArray()
  3. Printing array elements with foreach loop
  4. Printing list elements with Iterator (forward)
  5. Printing list elements with ListIterator (forward and backward).

List Tutorial Java
Output screenshot on List Tutorial Java

List, being an interface, cannot be instantiated, but its reference can be assigned by assigning its subclass object. We know a subclass object can be assigned to a super class object implicitly. ArrayList is derived from List interface. For all practical purposes, myList and yourList can be treated as objects of List.

Lists myList and yourList are added same elements. equals() method can be used to compare two lists. If they contain same elements, the method returns true else false.

Note: If a list contains another list as an element, equals() does not work properly.

In the second program, List Reversing Sorting, we have seen how to convert a string array into list. Now the above statement, converts the other way, list elements into an array.

With enhanced for loop (known as foreach loop), all the elements of the array are printed.

The iterator() method of list, the elements are printed.

listIterator() method of List returns an object ListIterator interface. ListIterator is derived from Iterator and added more features of traversing the elements in forward and backward direction. For forward iteration, it uses hasNext() and next() methods.

For backward iteration, hasPrevious() and previous() are used. See the screenshot.

Leave a Reply

Your email address will not be published. Required fields are marked *