Beruflich Dokumente
Kultur Dokumente
Java Core
Java SE
Java EE
Frameworks
IDEs
Servers
Coding
Books
Advertise
c Home
Java Core
Collections
Search...
Featured Books
Java Coding Guidelines:
Recommendations for
Reliable and Secure
Programs (SEI Series in
Software Engineering)
Head First Design Patterns
Java Concurrency in
Practice
Java Performance
Java Puzzlers: Traps, Pitfalls,
and Corner Cases
Head First Object-Oriented
Analysis and Design
Clean Code: A Handbook of
Agile Software
Craftsmanship
Algorithms Unlocked
Data Structures and
Algorithm Analysis in Java
(3rd Edition)
Refactoring: Improving the
Design of Existing Code
The Pragmatic Programmer:
From Journeyman to Master
Code Complete: A Practical
Handbook of Software
Construction, Second
Edition
Cracking the Coding
Interview: 150 Programming
Questions and Solutions
The Clean Coder: A Code of
Conduct for Professional
Programmers (Robert C.
Martin Series)
Clean Code
The Pragmatic
Programmer
List is a fundamental and widely-used collection type in the Java Collections
Framework. In this tutorial, well see characteristics of list collections, how to use list
implementations for day-to-day work and look at examples of common programming
practices when using lists.
Basically, a list collection stores elements by insertion order (either at the end or at a
specific position in the list). A list maintains indices of its elements so it allows adding,
retrieving, modifying, removing elements by an integer index (zero-based index; the
first element is at 0-index, the second at 1-index, the third at 2-index, and so on). The
following picture illustrates a list that stores some String elements:
A list can store objects of any types. Primitive types are automatically converted to
corresponding wrapper types, e.g. integer numbers are converted to Integerobjects.
It allows null and duplicate elements, and orders them by their insertion order (index).
The following class diagram depicts the primary methods defined in the
java.util.Listinterface:
The Listis the base interface for all list types, and the ArrayListand LinkedList
classes are two common Lists implementations.
ArrayList: An implementation that stores elements in a backing array. The
arrays size will be automatically expanded if there isnt enough room when
adding new elements into the list. Its possible to set the default size by
specifying an initial capacity when creating a new ArrayList. Basically, an
ArrayListoffers constant time for the following operations: size, isEmpty,
get, set, iterator, and listIterator; amortized constant time for the add
operation; and linear time for other operations. Therefore, this implementation
can be considered if we want fast, random access of the elements.
data structure. It offers constant time for adding and removing elements at the
end of the list; and linear time for operations at other positions in the list.
Therefore, we can consider using a LinkedListif fast adding and removing
elements at the end of the list is required.
Besides ArrayListand LinkedList,Vectorclass is a legacy collection and later was
retrofitted to implement the Listinterface. Vectoris thread-safe, but ArrayListand
LinkedListare not. The following class diagram depicts the inheritance tree of the
Listcollections:
1
2
3
4
5
6
7
The code examples in this tutorial revolve on the two common implementations:
ArrayListand LinkedList.
Its a good practice to declare a list instance with a generic type parameter, for
example:
1
2
3
4
Since Java 7, we can remove the type parameter on the right side as follows:
1
2
The compiler is able to infer the actual type parameter from the declaration on the left
side.
When creating a new ArrayListusing the empty constructor, the list is constructed
with an initial capacity of ten. If you are sure how many elements will be added to the
list, its recommended to specify a capacity which is large enough. Lets say, if we know
that a list contains around 1000 elements, declare the list as follows:
1
Its also possible to construct a list that takes elements from an existing collection, for
example:
1
2
3
The listNumberTwo constructed with copies of all elements from the listNumberOne.
We can insert an element into the list at a specified index, for example:
1
listStrings.add(1, "Four");
That inserts the String Four at the 2nd position in the list.
We can also add all elements of an existing collection to the end of the list:
1
listStrings.addAll(listWords);
listStrings.addAll(2, listWords);
Retrieving elements
The get()method is used to retrieve an element from the list at a specified index. For
example, the following code gets an element at 2nd position in the array list and an
element at 4th position in the linked list:
1
2
For a LinkedListimplementation, we can get the first and the last elements like this:
1
2
3
4
5
6
Updating elements
Use the set(index, element)method to replace the element at the specified index
by the specified element. For example:
1
listStrings.set(2, "Hi");
That replaces the 3rd element in the list by the new String Hi.
Removing elements
To remove an element from the list, use the remove(index)or remove(Object)
method which removes the element at the specified index or by object reference. For
example:
Remove the element at the 3rd position in the list:
1
listStrings.remove(2);
If the specified index is out of range (index < 0 or index >= list size), a
java.lang.IndexOutOfBoundsExceptionis thrown.
Remove the String element Two in the list:
1
listStrings.remove("Two");
if (listStrings.remove("Ten")) {
System.out.println("Removed");
} else {
System.out.println("There is no such element");
}
listStrings.clear();
Basically, we can use the enhanced for loop to iterate through all elements in the list,
as follows:
1
2
3
For more details and examples, see the tutorial: Java Collections Looping Example
To search for position of a specific element in the list or to know if the list contains the
element.
int indexOf(Object): returns the index of the first occurrence of the
if (listStrings.contains("Hello")) {
System.out.println("Found the element");
} else {
System.out.println("There is no such element");
}
int firstIndex = linkedNumbers.indexOf(1234);
int lastIndex = listStrings.indexOf("Hello");
Note that the above methods compare the elements using their equals()method, so if
you define your own type, make sure it implements the equals()method correctly.
The simplest way to sort out elements in a list is using the Collections.sort()static
method which sorts the specified list into ascending order, based on the natural
ordering of its elements. Heres an example:
1
2
3
4
5
6
7
8
9
10
11
12
Output:
1
2
Note that all elements in the list must implement the Comparableinterface, so if you
define your own type, make sure it implements that interface and its compareTo()
method.
For more details and examples, see the article: Sorting List Collections Examples
1
2
Note that you must manually synchronize the returned list when iterating over it, for
example:
1
2
3
4
5
6
synchronized (safeList) {
Iterator<Object> it = safeList.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
Ad d commen t
Name
comment
Comments
J C omments
About Advertise Contribute Contact Terms of Use Privacy Policy Site Map Newsletter
Copyright 2012 - 2014 by www.codejava.net