Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

At this point, the trimToSize() method can remove the unallocated space and change the capacity of the ArrayList so that it equals the number of elements in the ArrayList.

At this point, the trimToSize() method can remove the unallocated space and change the capacity of the ArrayList so that it equals the number of elements in the ArrayList.

Even before Java 2, Java provided ad-hoc classes. For example, Dictionary, Vector, Stack, and Properties were used to store and manipulate groups of objects.

Although these classes are very useful, they lack a core, unified theme. For this reason, the way of using the Vector class is quite different from the way of using the Properties class.

The collection framework was designed to meet the following goals.

To this end, the entire collection framework is designed around a set of standard interfaces. You can directly use the standard implementations of these interfaces, such as: LinkedList, HashSet, and LinkedHashMap, among others. TreeSet , etc. In addition, you can also implement your own collections through these interfaces.

From the collection framework diagram above, we can see that the Java collection framework mainly includes two types of containers: one is the collection (Collection), which stores a set of elements, and the other is the map (Map), which stores key/value pair mappings. The Collection interface has 3 subtypes: List, Set, and Queue; below them are some abstract classes, and finally the concrete implementation classes. Commonly used ones include ArrayList, LinkedList, HashSet, LinkedHashSet, HashMap, LinkedHashMap, and so on.

The collection framework is a unified architecture for representing and manipulating collections. All collection frameworks include the following:

In addition to collections, the framework also defines several Map interfaces and classes. A Map stores key/value pairs. Although Map is not a collection, it is fully integrated with collections.

The collection framework system is shown in the figure

The Java collection framework provides a set of high-performance, easy-to-use interfaces and classes. The Java collection framework is located in the java.util package, so you need to import the package when using the collection framework.


Collection Interfaces

The collection framework defines several interfaces. This section provides an overview of each interface:

No. Interface Description
1 Collection Interface

Collection is the most basic collection interface; a Collection represents a group of Objects, i.e., the elements of the Collection. Java does not provide classes that directly inherit from Collection, only sub-interfaces (such as List and Set) that inherit from it.

The Collection interface stores a group of non-unique, unordered objects.

2 List Interface

The List interface is an ordered Collection; using this interface allows precise control over the insertion position of each element, and access to elements in the List via an index (the position of the element in the List, similar to an array subscript), with the first element's index being 0, and duplicate elements are allowed.

The List interface stores a group of non-unique, ordered (insertion order) objects.

3 Set

Set has exactly the same interface as Collection, but with different behavior; Set does not store duplicate elements.

The Set interface stores a group of unique, unordered objects.

4 SortedSet
Inherits from Set and saves an ordered collection.
5 Map

The Map interface stores a group of key-value objects, providing a mapping from key to value.

6 Map.Entry
Describes an element (key/value pair) in a Map. It is an internal interface of Map.
7 SortedMap
Inherits from Map, keeping the Key in ascending order.
8 Enumeration
This is a legacy interface and defined methods through which you can enumerate (obtain one at a time) the elements in a collection of objects. This legacy interface has been replaced by the iterator.

Difference Between Set and List


Collection Implementation Classes

Java provides a set of standard collection classes that implement the Collection interface. Some are concrete classes that can be used directly, while others are abstract classes that provide partial implementations of the interface.

The standard collection classes are summarized in the table below:

No. Class Description
1 **AbstractCollection **
Implements most of the collection interfaces.
2 **AbstractList **
Inherits from AbstractCollection and implements most of the List interface.
3 **AbstractSequentialList **
Inherits from AbstractList, providing chained access to data elements rather than random access.
4 LinkedList
This class implements the List interface and allows null (empty) elements. It is mainly used to build linked-list data structures. This class has no synchronized methods, so if multiple threads access a List at the same time, you must implement access synchronization yourself; the solution is to construct a synchronized List when creating it. For example:
List list=Collections.synchronizedList(newLinkedList(...));

LinkedList has low search efficiency.

| | 5 | ArrayList

This class also implements the List interface and provides a resizable array, offering better performance for random access and element traversal. It is also not synchronized, so do not use it in multi-threaded situations. ArrayList grows by 50% of its current length; insertion and deletion are inefficient.

| | 6 | **AbstractSet **
Inherits from AbstractCollection and implements most of the Set interface. | | 7 | HashSet

This class implements the Set interface, does not allow duplicate elements, does not guarantee the order of elements in the collection, and allows at most one null element.

| | 8 | LinkedHashSet
with a predictable iteration order Set implementation of the interface based on a hash table and linked list. | | 9 | TreeSet

This class implements the Set interface and supports sorting.

| | 10 | **AbstractMap **
implements most of the Map interface. | | 11 | HashMap
HashMap is a hash table that stores key-value mappings.
This class implements the Map interface and stores data according to the key's hashCode value; it offers fast access, allows at most one record with a null key, and is not thread-synchronized. | | 12 | TreeMap
inherits from AbstractMap and uses a tree. | | 13 | WeakHashMap
inherits from the AbstractMap class; a hash table with weak keys. | | 14 | LinkedHashMap
inherits from HashMap and sorts elements by their natural order. | | 15 | IdentityHashMap
inherits from the AbstractMap class and uses reference equality when comparing entries. |

The classes defined in the java.util package have already been discussed in the previous tutorials, as shown below:

No. Class description
1 Vector

This class is very similar to ArrayList, but it is synchronized and can be used in multi-threaded situations. It allows a default growth length to be set, and by default it grows to twice its original size.

2 Stack
Stack is a subclass of Vector that implements a standard last-in, first-out stack.
3 Dictionary
The Dictionary class is an abstract class used to store key/value pairs; its role is similar to the Map class.
4 Hashtable

Hashtable is a subclass of the Dictionary class and is located in the java.util package.

5 Properties
Properties inherits from Hashtable and represents a persistent set of properties; each key and its corresponding value in the property list is a string.
6 BitSet
The Bitset class creates a special type of array that holds bit values. The size of the array in BitSet grows as needed.

Collection Algorithms

The collections framework defines several algorithms that can be used on collections and maps. These algorithms are defined as static methods of the collection classes.

When trying to compare incompatible types, some methods can throw a ClassCastException. When trying to modify an unmodifiable collection, an UnsupportedOperationException is thrown.

The collections define three static variables: EMPTY_SET, EMPTY_LIST and EMPTY_MAP. These variables are all immutable.

No. Algorithm description
1 Collection Algorithms
Here is a list of all the algorithm implementations.

How to use an iterator

Usually you will want to iterate over the elements in a collection, for example to display each element in the collection.

Normally arrays are traversed with a for loop or an enhanced for, and both can also be used with the collections framework; but there is another way — traversing the collections framework with an iterator, which is an object that implements theIterator interface or the ListIterator interface.

iterator that lets you obtain or remove collection elements through a loop. ListIterator extends Iterator to allow bidirectional traversal of a list and modification of elements.

No. Iterator method description
1 Using Java Iterator
Here, examples list all the methods provided by the Iterator and ListIterator interfaces.

Traversing an ArrayList

Example

import

java

.

util

.*;

public

class

Test

{

public

static

void

main

(

String

[

]

args

)

{

List

<
String
list
=
new
ArrayList
<
String
(
)

;

list

.

add

(

"

Hello

"

)

;

list

.

add

(

"

World

"

)

;

list

.

add

(

"

HAHAHAHA

"

)

;

//

The first traversal method uses For-Each to traverse a List

for

(

String

str

:

list

)

{

//

It can also be rewritten as for(int i=0;i

System

.

out

.

println

(

str

)

;

}

//

The second traversal converts the linked list into an array-like structure and traverses it

String

[

]

strArray

=

new

String

[

list

.

size

(

)

]

;

list

.

toArray

(

strArray

)

;

for

(

int

i

=

0

;

i

<

strArray

.

length

;

i

++

)

//

This can also be rewritten in the form for(String str:strArray)

{

System

.

out

.

println

(

strArray

[

i

]

)

;

}

//

The third traversal uses an iterator

Iterator

<
String
ite
=
list

.

iterator

(

)

;

while

(

ite

.

hasNext

(

)

)

//

Check whether there is a value after the next element

{

System

.

out

.

println

(

ite

.

next

(

)

)

;

}

}

}

**Analysis: **

All three methods traverse the ArrayList collection; the third uses an iterator, which avoids worrying about exceeding the collection length during traversal.

Traversing a Map

Example

import

java

.

util

.*;

public

class

Test

{

public

static

void

main

(

String

[

]

args

)

{

Map

<
String
,
String
map
=
new
HashMap
<
String
,
String
(
)

;

map

.

put

(

"

1

"

,

"

value1

"

)

;

map

.

put

(

"

2

"

,

"

value2

"

)

;

map

.

put

(

"

3

"

,

"

value3

"

)

;

//

The first: commonly used, with two value lookups

System

.

out

.

println

(

"

Traverse keys and values via Map.keySet:

"

)

;

for

(

String

key

:

map

.

keySet

(

)

)

{

System

.

out

.

println

(

"

key=

"

key

"

and value=

"

map

.

get

(

key

)

)

;

}

//

The second

System

.

out

.

println

(

"

Traverse keys and values via Map.entrySet with an iterator:

"

)

;

Iterator

<

Map

.

Entry

<
String
,
String
it
=
map

.

entrySet

(

)

.

iterator

(

)

;

while

(

it

.

hasNext

(

)

)

{

Map

.

Entry

<
String
,
String
entry
=
it

.

next

(

)

;

System

.

out

.

println

(

"

key=

"

entry

.

getKey

(

)

"

and value=

"

entry

.

getValue

(

)

)

;

}

//

The third: recommended, especially for large capacities

System

.

out

.

println

(

"

Traverse keys and values via Map.entrySet

"

)

;

for

(

Map

.

Entry

<
String
,
String
entry

:

map

.

entrySet

(

)

)

{

System

.

out

.

println

(

"

key=

"

entry

.

getKey

(

)

"

and value=

"

entry

.

getValue

(

)

)

;

}

//

The fourth

System

.

out

.

println

(

"

Traverse all values via Map.values(), but keys cannot be traversed

"

)

;

for

(

String

v

:

map

.

values

(

)

)

{

System

.

out

.

println

(

"

value=

"

v

)

;

}

}

}


How to use a comparator

TreeSet and TreeMap store elements in sorted order. However, a comparator is what precisely defines what that sort order is.

This interface lets us sort a collection in different ways.

No. Comparator method description
1 Using Java Comparator
Here, examples list all the methods provided by the Comparator interface

Summary

The Java collections framework provides programmers with pre-packaged data structures and algorithms to manipulate them.

A collection is an object that can hold references to other objects. Collection interfaces declare the operations that can be performed on each type of collection.

The classes and interfaces of the collections framework are all in the java.util package.

After any object is added to a collection class, it is automatically converted to the Object type, so a cast is required when retrieving it.