Summary of a collection based on Java Review

Source: Internet
Author: User

Java collections are mainly concentrated in two parts, one of which is java. in the util package, some are java. util. in concurrent, the latter defines a set of synchronization functions based on the former.

This article focuses on various collection objects under java. util. Collection objects in Java can be roughly divided into three categories: List, Set, and Map. The corresponding UML diagram is as follows (including most of the collection objects in java. util ):

Collection Overview

The List and Set in the Java Collection are all collected from the Collection. It is a good learning Set and contains the operations that are usually required in the Collection:

Add element: add/addAll
Clear collection: clear
Delete element: remove/removeAll
Determines whether the collection contains a certain element: contains/containsAll
Judge whether the set is empty: isEmpty
Number of elements in the calculation set: size
Convert a set to an array: toArray
Get iterator: iterator

Let's look at a simple example. The following code will return a set where elements are randomly generated integers:

Copy codeThe Code is 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 performing operations on a set, traversal is a frequently used operation. We can traverse the set in two ways:

1)Use the iterator to traverse the set. As described above in the Collection interface, all sets will have an iterator which we can use to traverse the set.

Copy codeThe Code is 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 set.Copy codeThe Code is 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 an effective extension to the array. It is such a structure. If you do not use generics, it can accommodate any type of elements. If you use generics, it can only accommodate elements of the specified type of the generic type. Compared with arrays, the List capacity can be dynamically expanded.

The elements in the List can be repeated. The elements in the List are "ordered". The "ordered" here does not mean sorting, instead, we can specify the position of an element in the set.

Commonly used collection objects in List include ArrayList, Vector, and sorted List. The first two are stored Based on arrays, and the latter is stored Based on linked lists. The Vector is thread-safe, and the other two are not thread-safe.

List can include null, even if the generic type is used.

ArrayList may be the most commonly used Collection object. In the sample code above, we also use it to instantiate a Collection object, which will not be repeated here.
Vector

The following is an example of Vector. First, let's look at how to generate and output a Vector:

Copy codeThe Code is 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 repeated elements and null. The output result is as follows:Copy codeThe Code is as follows: size of vector is 6
[100,100,100,100,100, null]

The following example demonstrates some common methods in Vector:Copy codeThe Code is as follows: private static void vectorTest2 ()
{
Vector <Integer> list = new Vector <Integer> ();
Random r = new Random ();
For (int I = 0; I <10; 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 );
}

The output result is as follows:
Copy codeThe Code is 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]

Shortlist

The linked list uses a linked list to store data. Its sample code is as follows:

Copy codeThe Code is as follows: Listing example
Private static void synchronized listtest1 ()
{
Counter list <Integer> list = new counter list <Integer> ();
Random r = new Random ();
For (int I = 0; I <10; 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 );
}

The Methods Commonly Used in the consumer list are listed here. From the method name, the consumer list can also be used to implement stacks and queues.

The output result is as follows:

Copy codeThe Code is as follows: size of linked list is 11
[17, 21, 5, 84, 19, 57, 68, 26, 27, 47, null]

Null

Null

Null

Size of linked list is 8
[100, 84, 19, 57, 68, 26, 27, 47]

Set

Similar to List, Set is used to store a single element. The quantity of a single element is uncertain. However, a Set cannot contain duplicate elements. If two identical elements are inserted into a Set, the latter element is not inserted.

Set can be roughly divided into two categories: unordered Set and sorted Set. unordered Set includes HashSet and sorted HashSet. Sorted Set mainly refers to TreeSet. HashSet and javashashset can contain null.
HashSet

A HashSet is a set supported by a Hash table. It is not thread-safe.

Let's take a look at the following example. It is basically the same as the first example of Vector:

Copy codeThe Code is 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, HashSet contains both repeated elements and null, which is different from Vector. The output result is as follows:Copy codeThe Code is as follows: size of set is 2
[Null, 100]

We can take a closer look at how HashSet judges whether two elements are repeated. The equals method is also defined in the Object. For elements in the HashSet, The equals method is used to determine whether the elements are equal. To prove this, we can define an "abnormal" type:Copy codeThe Code is as follows:Define a MyInteger object

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;
}
}

We can see that for MyInteger, we think it is not equal for any two instances.

The test method is as follows:

Copy codeThe Code is 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 );
}

The output result is as follows:Copy codeThe Code is as follows: size of set is 3
[100,100,100]

We can see that there are "repeated" elements in the HashSet, but they are not "identical" for MyInteger.
TreeSet

TreeSet is a Set that supports sorting. Its parent interface is SortedSet.

First, let's take a look at the basic operations of TreeSet:

Copy codeThe Code is 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 ));
}

The output result is as follows:Copy codeThe Code is as follows: [8, 42, 48, 49, 53]

[53, 49, 48, 42, 8]
[8, 42, 48, 49]
[53]
[42, 48, 49, 53]

Elements in the TreeSet generally implement the Comparable interface. By default, SortedList is stored in ascending order for integers. You can also customize the Compare method, for example, you can store data in descending order.

Next, we will first redefine Integer:

Copy codeThe Code is as follows: Define the MyInteger2 object
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 );
}
}

The following is the test code:Copy codeThe Code is 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 running result of the Code is as follows:Copy codeThe Code is as follows: Set1 as below:
[13, 41, 42, 45, 61]
Set2 as below:
[61, 45, 42, 41, 13]

Map

Map stores "key-value pairs". Similar to Set, Map in Java also has two types: sorted and unordered. unordered maps include HashMap, Hashtable, and LinkedHashMap, the sorting includes TreeMap.
Non-sorted Map

Both HashMap and Hashtable store data using Hash tables. HashMap is NOT thread-safe, and Hashtable is thread-safe. We can regard HashMap as a "simplified" version of Hashtable.

HashMap can store null values, either Key or Value. Hashtable cannot store null values.

Regardless of HashMap or Hashtable, we can observe its constructor and find that it has two parameters: initialCapacity and loadFactor. By default, initialCapacity is 16 and loadFactor is 0.75. This is related to the number of elements that can be stored in the Hash table. When the number of elements exceeds initialCapacity * loadFactor, the rehash method is triggered to expand the hash table. If we need to insert too many elements into it, we need to adjust these two parameters as appropriate.

Let's first look at the example of HashMap:

Copy codeThe Code is as follows: private static void hashMapTest1 ()
{
Map <Integer, String> map = new HashMap <Integer, String> ();

Map. put (new Integer (1), "");
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 outputs the Element Information in the HashMap, as shown below.Copy codeCode: {1 = a, 2 = B, 3 = c}
[1 = a, 2 = B, 3 = c]
[1, 2, 3]
[A, B, c]

The following example demonstrates null:Copy codeThe Code is 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 execution result is as follows:Copy codeCode: {null = null, 4 = null, 5 = null}
[Null = null, 4 = null, 5 = null]
[Null, 4, 5]
[Null, null, null]

Next we will demonstrate Hashtable, which is basically the same as the above two examples (the code is not expanded ):Copy codeThe Code is as follows: Hashtable example
Private static void hashTableTest1 ()
{
Map <Integer, String> table = new Hashtable <Integer, String> ();

Table. put (new Integer (1), "");
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 execution result is as follows:Copy codeCode: {3 = c, 2 = B, 1 =}
[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)

We can clearly see that when we try to insert null into hashtable, a null pointer exception is reported.
Sort Map

Sort Map mainly refers to TreeMap. It adds, deletes, and queries elements, and the time complexity is O (log (n )). It is not thread-safe.

Its features are very similar to TreeSet.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.