Summary of collections in Java

Source: Internet
Author: User
Tags set set sorts

The length of the Java array is fixed, in order for the program to conveniently store and manipulate a set of data that is not fixed, the JDK class library provides a Java collection that is located in the Java.util package, but unlike an array, the collection cannot hold the base type data, but only the object's reference.

The Java collection consists of the following three types:

Set: The objects in the collection are not sorted in a particular way, and there are no duplicate objects. Some of its implementation classes can sort the objects in the collection in a specially-ordered way.

List: Objects in the collection are sorted by index location, can have duplicate objects, and allow objects to be retrieved using an index.

Map: Each element in the collection contains a pair of key objects and value objects (Key-value), and the key objects in the collection cannot be duplicated, and some of its implementation classes can sort the key objects in the collection.

Class diagram of Java main collection class

Collection interface and iterator interface

A common method for set and list is declared in the collection interface:

Method Describe
Boolean Add (Object o) To include a reference to an object in the collection
void Clear () Delete all objects within the collection, i.e. no longer hold references to those objects
Boolean contains (Object o) Determines whether references to these objects are held in the collection
Boolean IsEmpty () Determines whether the collection is empty
Iterator Iterator () Returns a iterator object that can be used to iterate through the elements in the collection
Boolean remove (Object o) Remove a reference to an object from the collection
int size () Returns the number of elements in the collection
Object[] ToArray () Returns an array that contains all the elements in the collection

The Iterator Iterator () method returns a Iterator object, and the Iterator object takes a quick failure mechanism, for example, when a collection object is obtained through the Iterator () method of the Iterator object, The next () method that accesses the iterator object then throws a concurrentmodificationexception run-time exception by using some of the methods of the Ction collection to modify the collection.

The iterator interface provides a unified interface for traversing various types of collections. the iterator interface declares the following methods:

Method Describe
Hasnext () Determines whether the elements in the collection are traversed, and if not, returns true
Next () Returns the next element
Remove () Removes the previous element returned by the next () method from the collection

Set (SET)

Set is the simplest collection in which objects are not sorted in a particular way (no indexes), and no duplicate objects are in the collection. Set has two main implementation classes: HashSet and TreeSet. The HashSet class accesses the objects in the collection according to the hash algorithm, and when the object is added to the collection, Hahshset calls the object's Hashcode () method to obtain the hash code, and then computes the location of the object in the collection based on the hash code, so that the access speed is faster. The HashSet class also has a subclass Linkedhashset class, which not only implements the hashing algorithm, but also implements the linked list data structure. Linked list data structures can improve the performance of insert and delete elements. The TreeSet class implements the Sortset interface and has a sort function.

A reference to an object is stored in the set collection, and there is no duplicate object. The following example:

The result of the above program is 2. Therefore the Add () method of the set set is to use the Equals method to determine whether an object already exists in the collection. The difference between equals and "= =" is self-Google.

The TreeSet class implements the Sortset interface and has a sort function. The following example:

The result of the above program printing is 1 2 3 4. So when an object is inserted into the TreeSet collection, it is inserted into an ordered sequence of objects. TreeSet supports two sorts of sorting methods: natural sorting and custom sorting. By default, the natural sort method is used.

1. Natural sorting

Some classes in the JDK class library that have implemented the comparable interface are sorted in the following table:

Class Sort
Byte, Double, Float, Interger, Long, short Sort by number size
Character Sort by the numeric size of the Unicode value of the character
String Sort by the Unicode value of the characters in the string

2. Customized sequencing

We can customize the sort by implementing the Comparator<type> interface where type is the type that specifies the object being compared. The comparator interface has a compare (Type X,type y) method that compares the size of two objects when the return value is greater than 0. Indicates that x is greater than Y, and vice versa. The following example:

The first step is to implement the comparator interface

You can then automate the ordering of the clients:

The results of the above program printing are as follows:

List (lists)

The main feature of list lists is that their elements are stored in a linear fashion, allowing duplicate objects to be stored in the collection. the main implementation classes of the list interface include:

1, ArrayList: Represents a variable length array. Allows quick random access to elements (that is, retrieving elements at a particular index), but inserting and deleting elements in ArrayList is slower.

2, LinkedList: In the implementation of the linked list data structure, the sequential access is optimized to insert and delete elements in the faster, random access speed is slower. linklist documents have AddFirst (), AddLast (), GetFirst (), GetLast (), Removefirst (), Rmovelast () methods.

We can get the object at the specified index position through the get (int index) method. It can also be traversed by obtaining a iterator object.

List can only sort objects in the collection by index, and if you want to sort by other means, you can use the comparator interface and the collection class. The collection class is a helper class in the Java Collection Class library that provides a variety of static methods for manipulating the collection, where the sort () method is used to sort the objects in the list:

1. Sort (List List): Sort the objects in the list in a natural order.

2. Sort (List List,comparator Comparator): Sorts the objects in the list in a custom order.

Listiterator interface

The Listiterator () method of the list returns the Listiterator object. The Listiterator interface inherits from the iterator interface, and also provides a special way to manipulate the list:

Method Describe
Add () Insert an element into the list
Hasnext () Determines whether the elements in the collection are traversed, and if not, returns true
Hasprevious () Determines whether the elements in the collection have the previous element, and returns true if not
Next () Returns the next element
Previous () Returns the previous element

Compare the performance of Java arrays and various lists

The operating time obtained by the test:

type arraylist linkedlist
Random access operation (GET) 16 23 63
iterative operation (iterate) 31 33
insert operation (insert) Not applicable 1610 31
delete operation (remove) Not applicable 16

As can be seen from the table, the random access and iteration of the Java array has the fastest access speed, the LinkedList insert and delete operations have the fastest speed, the random access to the ArrayList also has a faster access speed.

Map (map)

Map (map) is a collection of key and value objects that are mapped. Using the Put (object key, Object value) to add elements to the map collection, you must supply a pair of key objects and value objects. Retrieves an element from the map collection using get (object key), so that the corresponding value object is returned whenever a key object is given.

The key object in the Map collection does not allow repetition, and after repeating the value object overrides the previous value object.

Map.entry represents a pair of keys and values in a map. The map's EntrySet () method returns a set set that holds elements of the map.entry type.

There are two more common implementations of map: HashMap and Treemap,hashmap have better access performance. TreeMap implements the SortedMap interface, which can sort the key objects, and also provides two ways of natural sorting and customized ordering.

New ways to iterate through a collection:

In addition to traversing the collection with iterator, you can also iterate over the collection with the following code:

Collection Utility Class: Collections

This class provides a series of static methods that manipulate a collection of list types.

Summary of collections in Java

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.