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.
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.
How to find length/size of ArrayList in Java? Example
You can use the size() method of java.util.ArrayList to find the length or size of ArrayList in Java. The size() method returns an integer equal to a number of elements present in the array list. It’s different than the length of the array which is backing the ArrayList, which is called the capacity of ArrayList . When you create an object of ArrayList in Java without specifying a capacity, it is created with a default capacity which is 10. Since ArrayList is a growable array, it automatically resizes when the size (number of elements in the array list) grows beyond a threshold.
Also, when an ArrayList is first created it is called empty ArrayList, and size() will return zero . If you add elements then size grows one by one. You can also remove all elements from ArrayList by using a clear() method which will then again make the ArrayList empty as shown in our examples.
ArrayList size() example in Java
Here is our sample Java program to demonstrate how to find the length or size of ArrayList in Java. As discussed it uses the size() method to return a number of elements in the array list but it is different than capacity which is equal to the length of the underlying array and always greater than the size.
The capacity is not publically exposed, as elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has a constant amortized time cost.
You can also use the trimToSize() method to trim the capacity of this ArrayList instance to be the list’s current size. An application can use this operation to minimize the storage of an ArrayList instance. See Core Java Volume 1 — Fundamentals book, or these free Java courses to learn more about essential collection classes and how they work.
Java Program to find number of elements in ArrayList
import java.util.ArrayList; /* * Java Program to find the length of ArrayList. * */ public class ArrayListDemo< public static void main(String[] args) < System.out.println("Welcome to Java Program to find the length of array list"); ArrayListString> listOfBanks = new ArrayList<>(); int size = listOfBanks.size(); System.out.println("size of array list after creating: " + size); listOfBanks.add("Citibank"); listOfBanks.add("Chase"); listOfBanks.add("Bank of America"); size = listOfBanks.size(); System.out.println("length of ArrayList after adding elements: " + size); listOfBanks.clear(); size = listOfBanks.size(); System.out.println("size of ArrayList after clearing elements: " + size); > > Output Welcome to Java Program to find length of array list the size of array list after creating: 0 the length of ArrayList after adding elements: 3 the length of ArrayList after clearing elements: 0
From the above example, you can see that the initial size of ArrayList was zero, which increased to 3 after adding 3 elements and it finally becomes zero when you called the clear() method on the ArrayList object. This method removes all elements from the array list making it empty again so that you can reuse it.
- How to reverse an ArrayList in Java? (solution)
- How to create and initialize the ArrayList in one line? (answer)
- How to declare ArrayList with values in Java? (example)
- How to convert an ArrayList to String in Java? (example)
- How to remove duplicates from ArrayList in Java? (example)
- How convert ArrayList to HashSet in Java? (example)
- How to get the first and last element of ArrayList in Java? (solution)
- How to loop over ArrayList in Java? (answer)
- How to get a range of elements as sublists from ArrayList in Java? (example)
- How to sort an ArrayList in Java? (answer)
- How to remove all elements of ArrayList in Java? (answer)
- How to remove a given element from ArrayList in Java? (answer)
How to find length of ArrayList in Java
You can find the length (or size) of an ArrayList in Java using size() method. The size() method returns the number of elements present in the ArrayList.
Syntax of size() method:
Program to find length of ArrayList using size()
In this program, we are demonstrating the use of size() method. As you can see, when arraylist is created, the size of it is zero. After adding few elements to the arraylist, the size of arraylist changed to 5 as we have done 5 additions using add() method. We then removed two elements from the arraylist using remove() method and printed the size again, which came as 3. This shows that the size() method returns the number of elements in a arraylist present at that particular moment of time.
import java.util.ArrayList; public class Details < public static void main(String [] args) < ArrayListal=new ArrayList(); System.out.println("Initial size: "+al.size()); al.add(1); al.add(13); al.add(45); al.add(44); al.add(99); System.out.println("Size after few additions: "+al.size()); al.remove(1); al.remove(2); System.out.println("Size after remove operations: "+al.size()); System.out.println("Final ArrayList: "); for(int num: al) < System.out.println(num); >> >
Initial size: 0 Size after few additions: 5 Size after remove operations: 3 Final ArrayList: 1 45 99
Another Example:
This is another example, where we have an arraylist of string type and we are using the size() method to find the length of arraylist after various add() and remove() operations.
import java.util.ArrayList; public class JavaExample < public static void main(String [] args) < ArrayListcityList=new ArrayList<>(); //adding elements to the arraylist cityList.add("Delhi"); cityList.add("Jaipur"); cityList.add("Agra"); cityList.add("Chennai"); //displaying current arraylist and size System.out.println("ArrayList: "+cityList); System.out.println("ArrayList size: "+cityList.size()); //removing an element from arraylist cityList.remove("Delhi"); //print arraylist and size System.out.println("ArrayList: "+cityList); System.out.println("ArrayList size: "+cityList.size()); > >
ArrayList: [Delhi, Jaipur, Agra, Chennai] ArrayList size: 4 ArrayList: [Jaipur, Agra, Chennai] ArrayList size: 3
Recommended articles:
Top Related Articles:
About the Author
I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.
Comments
Because when we remove element at first index, the element 45 moves to index 1 and 44 moves to index 2.Now when we remove(2) 44 will be deleted.