Why are lists useful in Java?

Differences Between Java List and Array List

Java is a dynamic language and can be used on any platform. It provides a Java List vs ArrayList. The list acts as an interface, and an Array list is an implementation of the list. The list interface consists of methods. These methods are included in the Array list class with a few additions of methods. The main difference between Java List vs ArrayList is that you need to create a reference to the parent interface in the first one and a reference to the class which implements the list. That means an Array list class is the second class. Let us have a look at the differences between Java List vs ArrayList.

Head to Head Comparison Between Java List and Array List [Infographics]

Below Is The Top 4 Comparison Between Java List vs Array List

Key Differences between Java List and Array List

The Differences Between Java List vs Array List are explained in the below-mentioned points:

  • One of the major differences is between Java List vs Array List is that list is an interface, and the Array list is a standard collection class.
  • The Java List interface extends the Collection, and the Array list extends the abstract listening class, and it can also implement the List interface.
  • List interface creates a collection of elements that are stored in sequence and can be accessed by its index number. Array list, on the contrary, creates an array of objects where the array can grow dynamically whenever required and reduce as well.
  • Both Java List vs Array List provides different kinds of methods to access data from the list. These methods enable getting elements from an array at the specified position and remove and shrink the size of an array in case of the Array list.

Java List vs Array List Comparisons Table

Following is the comparison table between Java List vs Array List

The basis of Comparison  Java List Array List
Basic difference The list is an interface that extends Collection. As it extends Collection it declares its behavior and stores a sequence of elements. A list can have some additional methods along with the ones present in the Collection. A list can also contain duplicate elements. Many of the methods in a list can throw Unsupported Operation Exception if the collection cannot be modified. Array List is a class that extends the Abstract List, and it implements the List interface. Normal arrays that are used in Java are of fixed length. Once an array is created in Java, its size cannot be increased or decreased. Array lists are dynamic and can be created with initial size, and later the size can be increased if more data is added, and also, it can be decreased if any data is removed.
Syntax The syntax to declare a list is as follows:

public interface List extends Collection

The syntax to declare an Array list is as follows:

public class ArrayList extends AbstractList implements List, RandomAccess, Cloneable, Serializable

Working Java List extends the Collection framework and uses the namespace system.collection.generic. A list is used to get objects that are related to their index numbers. A list object can be created as below: List a= new ArrayList[]; Once an object is created by a user can restrict the type of object which can be stored in the list. An object can be declared as type safe. This can be done as below:

// Obj is a type of object to be stored in List.List list = new List [];

An array list is created by extending AbstractList and implements the list interface. The namespace used by the Array list is System. Collections. The array list is considered when the user needs to create a dynamic array that contains objects and which can be added and removed at runtime. ArrayList is a class and hence provides a few constructors. These constructors are as below:

1]ArrayList[]: Using this constructor user can create an empty array list.2]ArrayList[Collection c]: This constructor is used to create an array list which is initialized with the elements which are sent in collection c.3]ArrayList[int capacity]: The main feature of Array list is that it increases automatically when more elements are added to the array list. This constructor helps to create an array list with a specified initial capacity.

Methods A list provides various methods: 1] void add[int index, Object obj] This method helps in inserting objects. This is done by invoking a list at the index that is being passed. Any existing elements are shifted, and as a result, no data is overwritten. 2] Object get[int index] It returns the object which is stored at that particular index within the invoking collection. 3] ListIterator listIterator[] This function returns an iterator to the start of the invoking list. 4] Object remove[int index] It is used in removing elements at the mentioned position index and returns the deleted item. Also, the resulting list is compressed, and indexes of subsequent elements are decremented by one. 5] List subList[int start, int end]

It will return a list from start to end where the start is the starting index, and the end will be the ending index. Elements in a list can also be referenced by the invoking object.

An array list provides the below methods: 1] void add[int index, Object obj] It inserts a specified element at a specified position and will throw an exception IndexOutOfBoundsException when the mentioned index is out of range. 2] Boolean contains[Object o] It searches the list and returns true if the element specified is present. To be more specific, if the list contains at least one element such that o==null? e==null : o.equals[e] 3] Object get[int index] It returns the element present at the specified position and will throw an exception IndexOutOfBoundsException when the mentioned index is out of range. 4] void ensureCapacity[int minCapacity] It increases the capacity of the Array list instance. It makes sure that it can hold a minimum number of elements which is specified as the capacity. 5]Object[] toArray[]

It returns an array that consists of all elements in the list. It returns NullPointerException if the array is null.

Conclusion

As a result, the array list is the solution to the problem of a memory of a static array. When a user uses an array list, the dynamic array is created, which can be increased whenever required. The normal list extends the collection class. Also, it is better to increase the capacity of an array in the beginning than reallocating the memory later. Manipulation is slow in the array list as shifting needs to be done if any element is removed from a list. In a list, you can perform different operations of positional access, searching and range view as well.

Recommended Article

This has been a guide to the top differences between Java List vs Array List. Here we also discuss the  key differences with infographics and comparison table. You may also have a look at the following articles to Learn more –

  • Type Parameters: E - the type of elements in this list All Superinterfaces: Collection, Iterable All Known Implementing Classes: AbstractList, AbstractSequentialList, ArrayList, AttributeList, CopyOnWriteArrayList, LinkedList, RoleList, RoleUnresolvedList, Stack, Vector
    public interface List extends Collection

    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.

    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.

    This interface is a member of the Java Collections Framework.

    Since: 1.2 See Also: Collection, Set, ArrayList, LinkedList, Vector, Arrays.asList[Object[]], Collections.nCopies[int, Object], Collections.EMPTY_LIST, AbstractList, AbstractSequentialList

      • parallelStream, removeIf, stream

      • int size[]

        Returns the number of elements in this list. If this list contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.

        Specified by: size in interface Collection Returns: the number of elements in this list
      • boolean isEmpty[]

        Returns true if this list contains no elements.

        Specified by: isEmpty in interface Collection Returns: true if this list contains no elements
      • boolean contains[Object o]

        Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that [o==null ? e==null : o.equals[e]].

        Specified by: contains in interface Collection Parameters: o - element whose presence in this list is to be tested Returns: true if this list contains the specified element Throws: ClassCastException - if the type of the specified element is incompatible with this list [optional] NullPointerException - if the specified element is null and this list does not permit null elements [optional]
      • Iterator iterator[]

        Returns an iterator over the elements in this list in proper sequence.

        Specified by: iterator in interface Collection Specified by: iterator in interface Iterable Returns: an iterator over the elements in this list in proper sequence
      • Object[] toArray[]

        Returns an array containing all of the elements in this list in proper sequence [from first to last element].

        The returned array will be "safe" in that no references to it are maintained by this list. [In other words, this method must allocate a new array even if this list is backed by an array]. The caller is thus free to modify the returned array.

        This method acts as bridge between array-based and collection-based APIs.

        Specified by: toArray in interface Collection Returns: an array containing all of the elements in this list in proper sequence See Also: Arrays.asList[Object[]]
      •  T[] toArray[T[] a]

        Returns an array containing all of the elements in this list in proper sequence [from first to last element]; the runtime type of the returned array is that of the specified array. If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list.

        If the list fits in the specified array with room to spare [i.e., the array has more elements than the list], the element in the array immediately following the end of the list is set to null. [This is useful in determining the length of the list only if the caller knows that the list does not contain any null elements.]

        Like the toArray[] method, this method acts as bridge between array-based and collection-based APIs. Further, this method allows precise control over the runtime type of the output array, and may, under certain circumstances, be used to save allocation costs.

        Suppose x is a list known to contain only strings. The following code can be used to dump the list into a newly allocated array of String:

        String[] y = x.toArray[new String[0]]; Note that toArray[new Object[0]] is identical in function to toArray[].

        Specified by: toArray in interface Collection Type Parameters: T - the runtime type of the array to contain the collection Parameters: a - the array into which the elements of this list are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose. Returns: an array containing the elements of this list Throws: ArrayStoreException - if the runtime type of the specified array is not a supertype of the runtime type of every element in this list NullPointerException - if the specified array is null
      • boolean add[E e]

        Appends the specified element to the end of this list [optional operation].

        Lists that support this operation may place limitations on what elements may be added to this list. In particular, some lists will refuse to add null elements, and others will impose restrictions on the type of elements that may be added. List classes should clearly specify in their documentation any restrictions on what elements may be added.

        Specified by: add in interface Collection Parameters: e - element to be appended to this list Returns: true [as specified by Collection.add[E]] Throws: UnsupportedOperationException - if the add operation is not supported by this list ClassCastException - if the class of the specified element prevents it from being added to this list NullPointerException - if the specified element is null and this list does not permit null elements IllegalArgumentException - if some property of this element prevents it from being added to this list
      • boolean remove[Object o]

        Removes the first occurrence of the specified element from this list, if it is present [optional operation]. If this list does not contain the element, it is unchanged. More formally, removes the element with the lowest index i such that [o==null ? get[i]==null : o.equals[get[i]]] [if such an element exists]. Returns true if this list contained the specified element [or equivalently, if this list changed as a result of the call].

        Specified by: remove in interface Collection Parameters: o - element to be removed from this list, if present Returns: true if this list contained the specified element Throws: ClassCastException - if the type of the specified element is incompatible with this list [optional] NullPointerException - if the specified element is null and this list does not permit null elements [optional] UnsupportedOperationException - if the remove operation is not supported by this list
      • boolean containsAll[Collection c]

        Returns true if this list contains all of the elements of the specified collection.

        Specified by: containsAll in interface Collection Parameters: c - collection to be checked for containment in this list Returns: true if this list contains all of the elements of the specified collection Throws: ClassCastException - if the types of one or more elements in the specified collection are incompatible with this list [optional] NullPointerException - if the specified collection contains one or more null elements and this list does not permit null elements [optional], or if the specified collection is null See Also: contains[Object]
      • boolean addAll[Collection

Chủ Đề