The collections in Java are concentrated in 2 parts, partly in the Java.util package, and partly in the Java.util.concurrent, which, based on the former, defines a set of synchronized functions.
This article focuses on the various collection objects under Java.util. The collection objects in Java can be roughly grouped into 3 categories: List, set, and map. The corresponding UML diagrams are as follows (including most of the collection objects under Java.util):
Collection Overview
The list and set in the Java collection come out of the collection, which is a good entry for a learning collection that contains the actions that are usually required in the collection:
add element: Add/addall
Empty collection: Clear
Delete element: Remove/removeall
To determine if an element is contained in the collection: Contains/containsall
To determine whether the collection is empty: IsEmpty
Count the number of elements in the collection: size
Convert a collection to an array: ToArray
Get iterator: Iterator
Let's look at a simple example where the following code returns a collection in which the elements in the collection are randomly generated integers:
Copy Code code as follows:
private static Collection initcollection ()
{
collection<integer> Collection = new arraylist<integer> ();
Random r = new Random ();
for (int i = 0; i < 5; i++)
{
Collection.add (New Integer (R.nextint (100));
}
return collection;
}
In the process of manipulating a collection, traversal is a frequently used operation, and we can iterate over the collection in two ways:
1 Iterate through the collection using an iterator. As described in the collection interface above, all collections have an iterator that we can use to traverse the collection.
Copy Code code as follows:
private static void Accesscollectionbyiterator (Collection<integer> Collection)
{
Iterator<integer> iterator = Collection.iterator ();
System.out.println ("The value in the list:");
while (Iterator.hasnext ())
{
System.out.println (Iterator.next ());
}
}
2)Use foreach to traverse the collection.
Copy Code code as follows:
private static void Accesscollectionbyfor (Collection<integer> Collection)
{
System.out.println ("The value in the list:");
for (Integer value:collection)
{
System.out.println (value);
}
}
List
The list in Java is a valid extension of an array, a structure that can hold any type of element if it is not used, and if it uses generics, it can hold only elements of the type specified by the generic type. The capacity of a list can be dynamically extended compared to arrays.
The elements in the list can be repeated, the elements inside are "ordered", the "order" here is not the meaning of the order, but rather we can specify the position of an element in the collection.
Common collection objects in the list include: ArrayList, Vector, and LinkedList, where the first two are stored based on an array, which is stored based on a linked list. Vector is thread safe, and the remaining two are not thread-safe.
The list can include NULL, even if the generics are used.
ArrayList may be the most common collection object we use, and in the example code above we use it to instantiate a collection object that we don't repeat here.
Vector
Vector For example, let's first look at how to generate and output vectors:
Copy Code code as follows:
private static void VectorTest1 ()
{
list<integer> list = new vector<integer> ();
for (int i = 0; i < 5; i++)
{
List.add (New Integer (100));
}
List.add (NULL);
SYSTEM.OUT.PRINTLN ("Size of vector is" + list.size ());
SYSTEM.OUT.PRINTLN (list);
}
Its elements include both repeating elements and null, and the output is as follows:
Copy Code code as follows:
Size of vector is 6
[MB, m, M, null]
The following example illustrates some of the common methods in vectors:
Copy Code code as follows:
private static void VectorTest2 ()
{
vector<integer> list = new vector<integer> ();
Random r = new Random ();
for (int i = 0; i < i++)
{
List.add (New Integer (R.nextint (100));
}
SYSTEM.OUT.PRINTLN ("Size of vector is" + list.size ());
SYSTEM.OUT.PRINTLN (list);
System.out.println (List.firstelement ());
System.out.println (List.lastelement ());
System.out.println (List.sublist (3, 8));
list<integer> temp = new arraylist<integer> ();
for (int i = 4; i < 7; i++)
{
Temp.add (List.get (i));
}
List.retainall (temp);
SYSTEM.OUT.PRINTLN ("Size of vector is" + list.size ());
SYSTEM.OUT.PRINTLN (list);
}
its output results are as follows:
Copy Code code as follows:
Size of Vector is 10
[39, 41, 20, 9, 29, 32, 54, 12, 94, 82]
[9, 29, 32, 54, 12]
Size of vector is 3
[29, 32, 54]
LinkedList
LinkedList uses a linked list to store data, and its sample code is as follows:
Copy Code code as follows:
LinkedList sample
private static void LinkedListTest1 ()
{
linkedlist<integer> list = new linkedlist<integer> ();
Random r = new Random ();
for (int i = 0; i < i++)
{
List.add (New Integer (R.nextint (100));
}
List.add (NULL);
SYSTEM.OUT.PRINTLN ("Size of linked list is" + list.size ());
SYSTEM.OUT.PRINTLN (list);
System.out.println (List.element ());
System.out.println (List.getfirst ());
System.out.println (List.getlast ());
System.out.println (List.peek ());
System.out.println (List.peekfirst ());
System.out.println (List.peeklast ());
System.out.println (List.poll ());
System.out.println (List.pollfirst ());
System.out.println (List.polllast ());
System.out.println (List.pop ());
List.push (New Integer (100));
SYSTEM.OUT.PRINTLN ("Size of linked list is" + list.size ());
SYSTEM.OUT.PRINTLN (list);
}
Here is a list of the common methods used by LinkedList, as can be seen from the method name, LinkedList can also be used to implement stacks and queues.
The output results are as follows:
Copy Code code as follows:
Size of linked list is 11
[5, G, G, G, MB, G, G
Null
Null
Null
Size of linked list is 8
[100, 84, 19, 57, 68, 26, 27, 47]
Set
Set and list are all used to store individual elements, and the number of individual elements is indeterminate. But set cannot contain duplicate elements, and if two identical elements are inserted into the set, the latter element will not be inserted.
Set can be roughly divided into two categories: unordered set and ordered set, unordered set including HashSet and Linkedhashset, and sort set mainly refers to TreeSet. where HashSet and linkedhashset can contain null.
HashSet
HashSet is a collection that is supported by a hash table and is not thread-safe.
Let's look at the following example, which is essentially the same as the first example of a vector:
Copy Code code as follows:
private static void HashSetTest1 ()
{
set<integer> set = new hashset<integer> ();
for (int i = 0; i < 3; i++)
{
Set.add (New Integer (100));
}
Set.add (NULL);
SYSTEM.OUT.PRINTLN ("Size of Set is" + set.size ());
SYSTEM.OUT.PRINTLN (set);
}
Here, the hashset contains both duplicate elements and null, unlike vectors, where the output is as follows:
Copy Code code as follows:
The size of set is 2
[NULL, 100]
We can delve into how hashset determines whether two elements are repetitive. The Equals method is also defined in object, and for elements in HashSet, it is based on the Equals method to determine whether the elements are equal, and to prove this we can define an "abnormal" type:
Copy Code code as follows:
Defining Myinteger Objects
Class Myinteger
{
private Integer value;
Public Myinteger (Integer value)
{
This.value = value;
}
Public String toString ()
{
return string.valueof (value);
}
public int hashcode ()
{
return 1;
}
public boolean equals (Object obj)
{
return true;
}
}
As you can see, for Myinteger, we think it's not equal for any two instances.
Here is the corresponding test method:
Copy Code code as follows:
private static void HashSetTest2 ()
{
set<myinteger> set = new hashset<myinteger> ();
for (int i = 0; i < 3; i++)
{
Set.add (New Myinteger (100));
}
SYSTEM.OUT.PRINTLN ("Size of Set is" + set.size ());
SYSTEM.OUT.PRINTLN (set);
}
Its output results are as follows:
Copy Code code as follows:
The size of set is 3
[100, 100, 100]
As you can see, there are "repeat" elements in the HashSet now, but for Myinteger, they are not "the same".
TreeSet
TreeSet is a set that supports sorting, and its parent interface is sortedset.
Let's start by looking at the basic operations of TreeSet:
Copy Code code as follows:
private static void TreeSetTest1 ()
{
treeset<integer> set = new treeset<integer> ();
Random r = new Random ();
for (int i = 0; i < 5; i++)
{
Set.add (New Integer (R.nextint (100));
}
SYSTEM.OUT.PRINTLN (set);
System.out.println (Set.first ());
System.out.println (Set.last ());
System.out.println (Set.descendingset ());
System.out.println (Set.headset) (New Integer (50));
System.out.println (Set.tailset) (New Integer (50));
System.out.println (Set.subset (30, 60));
System.out.println (Set.floor (50));
System.out.println (Set.ceiling (50));
}
Its output results are as follows:
Copy Code code as follows:
[8, 42, 48, 49, 53]
[53, 49, 48, 42, 8]
[8, 42, 48, 49]
[53]
[42, 48, 49, 53]
The elements in TreeSet generally implement the comparable interface, by default, SortedList are stored in ascending order for integers, and we can customize the compare way, for example, in descending order.
Next, we first redefine the integer:
Copy Code code as follows:
Defining MyInteger2 Objects
Class MyInteger2 implements comparable
{
public int value;
public MyInteger2 (int value)
{
This.value = value;
}
public int CompareTo (Object arg0)
{
MyInteger2 temp = (MyInteger2) arg0;
if (temp = null) return-1;
if (Temp.value > This.value)
{
return 1;
}
else if (Temp.value < This.value)
{
return-1;
}
return 0;
}
public boolean equals (Object obj)
{
return CompareTo (obj) = = 0;
}
Public String toString ()
{
return string.valueof (value);
}
}
Here is the test code:
Copy Code code as follows:
private static void TreeSetTest2 ()
{
treeset<integer> Set1 = new treeset<integer> ();
treeset<myinteger2> Set2 = new treeset<myinteger2> ();
Random r = new Random ();
for (int i = 0; i < 5; i++)
{
int value = r.nextint (100);
Set1.add (new Integer (value));
Set2.add (new MyInteger2 (value));
}
System.out.println ("Set1 as below:");
System.out.println (SET1);
System.out.println ("Set2 as below:");
System.out.println (Set2);
}
The code runs as expected, as follows:
Copy Code code as follows:
Set1 as below:
[13, 41, 42, 45, 61]
Set2 as below:
[61, 45, 42, 41, 13]
Map
The map Stores "key-value pairs," similar to the set, and there are two kinds of maps in Java: Sorted and unordered, unordered, including HashMap, Hashtable, and Linkedhashmap, sorted by TreeMap.
Non-sorted map
HashMap and Hashtable are stored in a hash table, HashMap is not thread-safe, Hashtable is thread-safe, and we can think of HashMap as a "simplified" version of Hashtable.
HashMap can store null, whether it is on key or value. Hashtable is not available to store null.
Whether HashMap or Hashtable, we look at its constructor and find that it can have two parameters: Initialcapacity and Loadfactor, by default, Initialcapacity equals 16, Loadfactor equals 0.75. This is related to the number of elements that can be stored in the hash table, and when the number of elements exceeds initialcapacity*loadfactor, the rehash method is triggered to enlarge the hash table. If we need to insert too many elements into it, we need to adjust these two parameters appropriately.
Let's first look at the HashMap example:
Copy Code code as follows:
private static void HashMapTest1 ()
{
map<integer,string> map = new Hashmap<integer, string> ();
Map.put (New Integer (1), "a");
Map.put (New Integer (2), "B");
Map.put (New Integer (3), "C");
SYSTEM.OUT.PRINTLN (map);
System.out.println (Map.entryset ());
System.out.println (Map.keyset ());
System.out.println (Map.values ());
}
This will output the element information in the HashMap, as shown below.
Copy Code code as follows:
{1=a, 2=b, 3=c}
[1=a, 2=b, 3=c]
[1, 2, 3]
[A, B, c]
The following example is a demonstration of NULL:
Copy Code code as follows:
private static void HashMapTest2 ()
{
map<integer,string> map = new Hashmap<integer, string> ();
Map.put (null, NULL);
Map.put (null, NULL);
Map.put (New Integer (4), NULL);
Map.put (New Integer (5), NULL);
SYSTEM.OUT.PRINTLN (map);
System.out.println (Map.entryset ());
System.out.println (Map.keyset ());
System.out.println (Map.values ());
}
The results of the implementation are as follows:
Copy Code code as follows:
{null=null, 4=null, 5=null}
[Null=null, 4=null, 5=null]
[NULL, 4, 5]
[NULL, NULL, NULL]
Next we show Hashtable, which is essentially exactly the same as the previous two examples (code no longer expands):
Copy Code code as follows:
Hashtable sample
private static void HashTableTest1 ()
{
map<integer,string> table = new Hashtable<integer, string> ();
Table.put (New Integer (1), "a");
Table.put (New Integer (2), "B");
Table.put (New Integer (3), "C");
SYSTEM.OUT.PRINTLN (table);
System.out.println (Table.entryset ());
System.out.println (Table.keyset ());
System.out.println (Table.values ());
}
private static void HashTableTest2 ()
{
map<integer,string> table = new Hashtable<integer, string> ();
Table.put (null, NULL);
Table.put (null, NULL);
Table.put (New Integer (4), NULL);
Table.put (New Integer (5), NULL);
SYSTEM.OUT.PRINTLN (table);
System.out.println (Table.entryset ());
System.out.println (Table.keyset ());
System.out.println (Table.values ());
}
The results of the implementation are as follows:
Copy Code code as follows:
{3=c, 2=b, 1=a}
[3=c, 2=b, 1=a]
[3, 2, 1]
[C, B, a]
Exception in thread "main" java.lang.NullPointerException
At Java.util.Hashtable.put (Unknown Source)
At Sample.collections.MapSample.hashTableTest2 (mapsample.java:61)
At Sample.collections.MapSample.main (mapsample.java:11)
It is clear to see that when we attempt to insert null into Hashtable, NULL pointer exceptions are reported.
Sort Map
The sort map mainly refers to the TreeMap, which has an O (log (n)) for the time complexity of adding, deleting and searching the elements. It is not thread-safe.
Its characteristics and TreeSet is very similar, here no longer repeat.