Java Collections Overview

Source: Internet
Author: User

There are many collections in Java: List,arraylist,vector,hashsettreeset, the differences between them, the framework of the Java collection, and so on are always vague, saying there is time to summarize.

One, collection interface and iterator interface

1.Collection Frame:

The collection interface mainly defines some methods for manipulating the set elements:

boolean

Add ( E e)

Ensures that this collection contains the specified element (optional operation). Returns true if the insert succeeds

boolean

AddAll ( Collection <? extends E> c)

Adds all of the elements in the specified collection to this collection (optional operation). Change returns True

void

Clear()

Removes all of the elements from this collection (optional operation).

boolean

contains ( Object o)

Returns True If this collection contains the specified element.

boolean

Containsall ( Collection<?> c)

Returns True If this collection contains all of the elements in the specified collection.

boolean

equals ( Object o)

Compares the specified object with this collection for equality.

int

Hashcode()

Returns the hash code value for this collection.

。。。。。。 See the document in detail

2. Traversing geometric elements using the iterator interface

The Iterrator interface hides the details of the various collection implementation classes, providing the application with a unified programming interface that iterates through the collection collection elements. The following three methods are defined in the iterator interface:

Boolean hashnext (): Returns True if the collection element that is iterated has not been traversed.

Object Next (): Returns the next element in the collection.

Void Remove (): Deletes the element returned by the previous next method in the collection.

* * When accessing collection collection elements using iterator iterations, the elements in the collection collection cannot be changed, only the collection elements returned by the previous next method are deleted by the Remove method of the iterator. Otherwise, a java.util.Concurrent modificationexception exception will be thrown.

Let's start with a class introduction

Second, set set

The Set collection method is essentially the same as collection, and it does not provide an additional method. The set is actually collection, but behaves slightly differently (set does not allow repeating elements).

Set determines whether two objects are the same according to the Equals method. That is, as long as two objects are compared using the Equals method method to return False,set, the two objects are accepted.

1.HashSet is a typical implementation of set, HashSet to the hash algorithm to store the elements in the collection, so it has good access and lookup performance.

Features: The ordering of elements cannot be guaranteed; not synchronous, not thread safe; The collection value can be null.

The HashSet set determines that the equivalent of two elements is two objects that are equal by the Equals method, and that the return value of the Hashcode () method of two objects is also equal.

Example:

The Equals method of the import java.util.*;//class A always returns TRUE, but does not override its Hashcode () method class A{public Boolean equals (Object obj) {return true;}} The Hashcode () method of Class B always returns 1, but does not override its Equals () method class B{public int hashcode () {return 1;}} The Hashcode () method of class C always returns 2, but does not override its Equals () method class C{public int hashcode () {return 2;} public boolean equals (Object obj) {return true;}} public class Testhashset{public static void Main (string[] args) {HashSet books = new HashSet ();//Add 2 a objects to the books collection, 2 B objects respectively , 2 C Objects Books.add (new A ()), Books.add (New A ()), Books.add (new B ()); Books.add (new B ()); Books.add (new C ()); Books.add (new C ()); SYSTEM.OUT.PRINTLN (books);}}

Output: [[email protected], [email protected], [email protected], [email protected], [email protected]]

It can be seen that hashset a, B as two objects, C only one.

2.LinkedHashSet class

The Linkedhashset collection also determines where the element is stored, based on the hashcode value of the element, but it maintains the order of the elements using the linked list. This makes the elements appear to be saved in an insertion order, that is, when the collection is traversed, Linkedhashset will access the elements of the collection in the order in which they are added.

Linkedhashset performance is better than hashset when iterating through all the elements in the set, but the performance is slightly inferior to hashset at insert time.

Import java.util.*;p ublic class testlinkedhashset{public static void Main (string[] args) {Linkedhashset books = new Linked HashSet (); Books.add ("first"); Books.add ("second");//Remove Struts2 authoritative guide books.remove ("first");//Add Struts2 authoritative guide books.add ("first "); SYSTEM.OUT.PRINTLN (books);//[second, first]}}

Output: [Second, first] you can see that the order is in the order of insertion.

3.TreeSet class

TreeSet is an implementation class for the SortedSet interface, and TreeSet ensures that the collection element is in the sorted state. TreeSet supports two sorting methods, natural sorting and custom sorting, in which the natural sort is the default sorting method. The object that is added to the treeset should be the same class.

TreeSet determines that two objects are not equal by two objects that return false through the Equals method, or 0 is not returned by the CompareTo method. Objects that are added to the treeset should be of the same class, and preferably an immutable object.

1. Natural sorting

Natural sorting uses the CompareTo (Object obj) method to sort the elements to compare the size relationships between elements, and then arranges the elements in ascending order.

Java provides a comparable interface that defines a CompareTo (object obj) method that returns an integer value that implements the object of the interface to compare the size.

The Obj1.compareto (obj2) method returns 0, indicating that the two objects being compared are equal, and if a positive number is returned, the OBJ1 is greater than obj2, and if it is negative, obj1 is less than obj2.

If we always return true for the Equals method of two objects, then the CompareTo method returned by the two objects should return a 0

Import Java.util.*;class R implements Comparable{int count;public r (int count) {This.count = count;} Public String toString () {return "R" (Count property: "+ Count +") ";} public boolean equals (Object obj) {if (obj instanceof R) {R r = (r) obj;if (R.count = = This.count) {return true;}} return false;} public int compareTo (Object obj) {r r = (r) obj;if (This.count > R.count) {return 1;} else if (This.count = = r.count) {return 0;} else{return-1;}}} public class Testtreeset2{public static void Main (string[] args) {TreeSet ts = new TreeSet (); Ts.add (new R (5)); Ts.add (New R (-3)); Ts.add (New R (9)); Ts.add (New R (-2));//Print TreeSet collection, the collection element is an ordered System.out.println (TS);//Take out the first element. ;//Assigns a value to the Count property of the first element first.count = 20;//takes the last element R = (r) ts.last ();//assigns a value to the Count property of the last element, the same as the second-lowest element, the Count property Last.count = -2;//again output count will see the elements in the TreeSet in an unordered state, and there are repeating elements System.out.println (TS);//delete the element that the attribute was changed, delete the failed ts.remove (new R (-2)); SYSTEM.OUT.PRINTLN (TS);//delete the attribute without changing the element, delete the successful ts.remove (new R (5));
Ts.remove (New R (20)); SYSTEM.OUT.PRINTLN (TS);}}

Output Result:

/*
----------Java Run----------
[R (Count property:-3), R (Count property:-2), R (Count property: 5), R (Count property: 9)]
[R (Count property:), R (Count property:-2), R (Count property: 5), R (Count property:-2)]//The change is not reordered here, so it is best to put an immutable object in the TreeSet.
[R (Count property:), R (Count property:-2), R (Count property: 5), R (Count property:-2)]//Delete-2 failed because the property was changed
[R (Count property:), R (Count property:-2), R (Count property:-2)]//No change of 5 can be deleted

Output complete (0 seconds)-Normal termination */

2. Custom sorting

Natural sorting is based on the size of the collection elements, in ascending order, if you want to customize the sorting, you should use the comparator interface to implement the int compare (T o1,t O2) method, which is used to compare the size of O1 and O2: If the method returns a positive integer, the O1 is greater than O2 If the method returns 0, the O1 equals O2 and if the method returns a negative integer, the O1 is less than O2.

If you need to customize the ordering, you need to provide a comparator object associated with the TreeSet collection when you create the TreeSet collection, and the comparator object is responsible for the sorting logic of the geometry elements:

Import Java.util.*;class m{int age;public M (int age) {this.age = age;} Public String toString () {   return ' M Age: ' +age;}} public class Testtreeset3{public static void Main (string[] args) {TreeSet ts = new TreeSet (new Comparator () {public int com Pare (object O1, Object O2) {/*int age1 = O1 instanceof M? ((M) O1). Age:((N) O1). Age;int age2 = O1 instanceof M? ((m) O2). Age:((N) O2). Age;return age1-age2;*/m m1 = (m) O1; M m2 = (m) o2;if (M1.age > M2.age) {return-1;} else if (m1.age = = m2.age) {return 0;} Else{return 1;}}); Ts.add (new M (5)); Ts.add (new M ( -3)); Ts.add (new M (9)); SYSTEM.OUT.PRINTLN (TS);//[m Age:9, M age:5, M age:-3]}}

Output results • (descending): [M Age:9, M Age:5, M age:-3]

4. Comparison of each set implementation class:

HashSet and TreeSet are the two typical implementations of set, and the performance of HashSet is better than treeset (especially the most commonly used additions, query elements, and so on). TreeSet should only be used if a set to keep sort is needed, otherwise use hashset

Linkedhashset: For a normal insert delete operation, it is slower than hashset and the traversal is faster.

In addition: The three implementations of set Hashset,treeset and Enemset are thread insecure, and if there are multiple threads accessing a set set, you must manually keep the synchronization:

Tool classes available with collections: for example:

SortedSet s = collections.synchronizedsortedset (new TreeSet (...));

The set set is finally summed up.

This is long enough, list set in the next article ...

Forwarding Please specify: http://www.cnblogs.com/jycboy/p/set.html

Java Collections Overview

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.