Java list of extended class

Interface List

An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2) , and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare.

The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator , add , remove , equals , and hashCode methods. Declarations for other inherited methods are also included here for convenience.

The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.

The List interface provides a special iterator, called a ListIterator , that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.

Читайте также:  Javascript require with arguments

The List interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches.

The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list.

Note: While it is permissible for lists to contain themselves as elements, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a list.

Some list implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException . Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the list may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as «optional» in the specification for this interface.

Unmodifiable Lists

  • They are unmodifiable. Elements cannot be added, removed, or replaced. Calling any mutator method on the List will always cause UnsupportedOperationException to be thrown. However, if the contained elements are themselves mutable, this may cause the List’s contents to appear to change.
  • They disallow null elements. Attempts to create them with null elements result in NullPointerException .
  • They are serializable if all elements are serializable.
  • The order of elements in the list is the same as the order of the provided arguments, or of the elements in the provided array.
  • The lists and their subList views implement the RandomAccess interface.
  • They are value-based. Programmers should treat instances that are equal as interchangeable and should not use them for synchronization, or unpredictable behavior may occur. For example, in a future release, synchronization may fail. Callers should make no assumptions about the identity of the returned instances. Factories are free to create new instances or reuse existing ones.
  • They are serialized as specified on the Serialized Form page.

This interface is a member of the Java Collections Framework.

Источник

Java List — List in Java

Java List - List in Java

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Java List is an ordered collection. Java List is an interface that extends Collection interface. Java List provides control over the position where you can insert an element. You can access elements by their index and also search elements in the list.

Java List

  • Java List interface is a member of the Java Collections Framework.
  • List allows you to add duplicate elements.
  • List allows you to have ‘null’ elements.
  • List interface got many default methods in Java 8, for example replaceAll, sort and spliterator.
  • List indexes start from 0, just like arrays.
  • List supports Generics and we should use it whenever possible. Using Generics with List will avoid ClassCastException at runtime.

Java List Class Diagram

java list, java list example, java list tutorial, java list interface, java list class diagram

Java List interface extends Collection interface. Collection interface externs Iterable interface. Some of the most used List implementation classes are ArrayList, LinkedList, Vector, Stack, CopyOnWriteArrayList. AbstractList provides a skeletal implementation of the List interface to reduce the effort in implementing List.

Java List Methods

Some of the useful Java List methods are;

  1. int size(): to get the number of elements in the list.
  2. boolean isEmpty(): to check if list is empty or not.
  3. boolean contains(Object o): Returns true if this list contains the specified element.
  4. Iterator iterator(): Returns an iterator over the elements in this list in proper sequence.
  5. Object[] toArray(): Returns an array containing all of the elements in this list in proper sequence
  6. boolean add(E e): Appends the specified element to the end of this list.
  7. boolean remove(Object o): Removes the first occurrence of the specified element from this list.
  8. boolean retainAll(Collection c): Retains only the elements in this list that are contained in the specified collection.
  9. void clear(): Removes all the elements from the list.
  10. E get(int index): Returns the element at the specified position in the list.
  11. E set(int index, E element): Replaces the element at the specified position in the list with the specified element.
  12. ListIterator listIterator(): Returns a list iterator over the elements in the list.
  13. List subList(int fromIndex, int toIndex): Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa.

Some of the default methods added to List in Java 8 are;

  1. default void replaceAll(UnaryOperator operator): Replaces each element of this list with the result of applying the operator to that element.
  2. default void sort(Comparator c): Sorts this list according to the order induced by the specified Comparator.
  3. default Spliterator spliterator(): Creates a Spliterator over the elements in this list.

Java Array to List

We can use Arrays class to get the view of array as list. However we won’t be able to do any structural modification to the list, it will throw java.lang.UnsupportedOperationException. So the best way is to use for loop for creating list by iterating over the array. Below is a simple example showing how to convert java array to list properly.

package com.journaldev.examples; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ArrayToList < public static void main(String[] args) < String[] vowels = ; List vowelsList = Arrays.asList(vowels); System.out.println(vowelsList); /** * List is backed by array, we can't do structural modification * Both of the below statements will throw java.lang.UnsupportedOperationException */ //vowelsList.remove("e"); //vowelsList.clear(); //using for loop to copy elements from array to list, safe for modification of list List myList = new ArrayList<>(); for(String s : vowels) < myList.add(s); >System.out.println(myList); myList.clear(); > > 

Choose any of the above methods based on your project requirements.

Java List to Array

A simple example showing the correct way to convert a list to array.

package com.journaldev.examples; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ListToArray < public static void main(String[] args) < Listletters = new ArrayList(); // add example letters.add("A"); letters.add("B"); letters.add("C"); //convert list to array String[] strArray = new String[letters.size()]; strArray = letters.toArray(strArray); System.out.println(Arrays.toString(strArray)); //will print "[A, B, C]" > > 

Java List sort

There are two ways to sort a list. We can use Collections class for natural sorting or we can use List sort() method and use our own Comparator for sorting. Below is a simple example for java list sorting.

package com.journaldev.examples; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; public class ListSortExample < public static void main(String[] args) < Listints = new ArrayList<>(); Random random = new Random(); for (int i = 0; i < 10; i++) ints.add(random.nextInt(1000)); //natural sorting using Collections class Collections.sort(ints); System.out.println("Natural Sorting: "+ints); //My custom sorting, reverse order ints.sort((o1,o2) ->); System.out.println("Reverse Sorting: "+ints); > > 

A sample output is given below. Since I am using Random for generating list elements, it will be different every time.

Natural Sorting: [119, 273, 388, 450, 519, 672, 687, 801, 812, 939] Reverse Sorting: [939, 812, 801, 687, 672, 519, 450, 388, 273, 119] 

Java List Common Operations

Most common operations performed on java list are add, remove, set, clear, size etc. Below is a simple java list example showing common method usage.

package com.journaldev.examples; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ListExample < public static void main(String args[]) < Listvowels= new ArrayList(); //add example vowels.add("A"); vowels.add("I"); //let's insert E between A and I vowels.add(1,"E"); System.out.println(vowels); List list = new ArrayList(); list.add("O");list.add("U"); //appending list elements to letters vowels.addAll(list); System.out.println(vowels); //clear example to empty the list list.clear(); //size example System.out.println("letters list size = "+vowels.size()); //set example vowels.set(2, "E"); System.out.println(vowels); //subList example vowels.clear();vowels.add("E"); vowels.add("E");vowels.add("I"); vowels.add("O"); list = vowels.subList(0, 2); System.out.println("letters = "+vowels+", list = "+list); vowels.set(0, "A"); System.out.println("letters = "+vowels+", list = "+list); list.add("U"); System.out.println("letters = "+vowels+", list = "+list); > > 

Output of above java list example program is;

[A, E, I] [A, E, I, O, U] letters list size = 5 [A, E, E, O, U] letters = [E, E, I, O], list = [E, E] letters = [A, E, I, O], list = [A, E] letters = [A, E, U, I, O], list = [A, E, U] 

Java List iterator

Below is a simple example showing how to iterate over list in java.

package com.journaldev.examples; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ListIteratorExample < public static void main(String[] args) < Listlist = new ArrayList<>(); for(int i=0; i <5; i++) list.add(i); Iteratoriterator = list.iterator(); //simple iteration while(iterator.hasNext()) < int i = (int) iterator.next(); System.out.print(i + ", "); >System.out.println("\n"+list); //modification of list using iterator iterator = list.iterator(); while(iterator.hasNext()) < int x = (int) iterator.next(); if(x%2 ==0) iterator.remove(); >System.out.println(list); //changing list structure while iterating iterator = list.iterator(); while(iterator.hasNext()) < int x = (int) iterator.next(); //ConcurrentModificationException here if(x==1) list.add(10); >> > 

Output of above java list iterator program is;

0, 1, 2, 3, 4, [0, 1, 2, 3, 4] [1, 3] Exception in thread "main" java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901) at java.util.ArrayList$Itr.next(ArrayList.java:851) at com.journaldev.examples.ListIteratorExample.main(ListIteratorExample.java:34) 

That’s all of a quick roundup on List in Java. I hope these Java List examples will help you in getting started with List collection programming.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Оцените статью