Set of Java Collections

Source: Internet
Author: User
Tags comparable set set

The Java collection can be broadly divided into: set,list,map three systems, where set represents an unordered collection, a list represents an ordered and repeatable collection, and a map represents a collection with a mapping relationship. Later, a set of queue systems is added, representing a collection of queues.

Both the set and list interfaces implement the collection interface

Traversing a collection element using the iterator interface
Import java.util.Collection;
Import Java.util.HashSet;
Import Java.util.Iterator;

public class Testiterator {

/**
* @param args
*/
public static void Main (string[] args) {
TODO auto-generated Method Stub
Create a Collection
Collection books = new HashSet ();
Books.add ("Book1");
Books.add ("Book2");
Books.add ("Book3");
Books.add ("Book4");
Get iterator iterator
Iterator it = Books.iterator ();
while (It.hasnext ()) {
The data type returned by the It.next () method is of type object and requires casting of type
String book = (string) it.next ();
SYSTEM.OUT.PRINTLN (book);
if (Book.equals ("Book3")) {
Removes the element from the collection that was last returned by next
It.remove ();
The collection element cannot be modified while using the iterator iterator, so the following code throws an exception
Books.remove ("Book3");
}
Assigning a value to a book variable does not alter the element itself
book= "Book9";
}
SYSTEM.OUT.PRINTLN (books);
}

}

Iterator must be attached to the collection object. There is a iterator object, there is bound to be a collection object associated with it.

Using foreach to iterate through collection elements is more concise
Import java.util.Collection;
Import Java.util.HashSet;

public class Testiterator {

/**
* @param args
*/
public static void Main (string[] args) {
TODO auto-generated Method Stub
Create a Collection
Collection books = new HashSet ();
Books.add ("Book1");
Books.add ("Book2");
Books.add ("Book3");
Books.add ("Book4");
for (Object obj:books)
{
String book = (string) obj;
SYSTEM.OUT.PRINTLN (book);
if (Book.equals ("Book3")) {

The collection element cannot be modified using the loop procedure, so the following code throws an exception
Books.remove ("Book3");
}
}

SYSTEM.OUT.PRINTLN (books);
}

}

Set interface

The set is actually collection, but the set does not allow repeating elements to be included

Set the Equals method to determine whether two objects are the same, not = =, so as long as equals returns True, two objects are the same, regardless of how large the two objects differ, and as long as equals returns false, even if two objects are actually the same object. Set is also treated as a two object.
For example:
Import Java.util.HashSet;
Import Java.util.Set;

public class Testset {

/**
* @param args
*/
public static void Main (string[] args) {
TODO auto-generated Method Stub
Set books = new HashSet ();
Books.add ("Book1");
Boolean result = Books.add (new String ("Book1"));
SYSTEM.OUT.PRINTLN (result);
SYSTEM.OUT.PRINTLN (books);
}

}
Will output false Book1

Hashset,treeset,enumset Three classes implement the set interface

HashSet class
HashSet has the characteristics of:
1 There is no guarantee that the order of the elements will change.
2 HashSet is not synchronous, if more than one thread accesses a set set at the same time, if more than one thread accesses a hashset at the same time, if there are 2 or more threads modifying the HashSet collection, The code must be guaranteed to be synchronous (TreeSet and Enumset as well).
3 The collection element can be null.

HashSet judge that two elements are equal the standard is that two objects are compared by the Equals method, and the value returned by the Hashcode method of two objects is also equal.
If Equals is equal and the hashcode return value is different, then HashSet will save the two objects to a different location, adding the success
If Equals is not equal, the hashcode return value is equal, then HashSet will attempt to save two objects in the same location, in fact, it will be difficult to handle and will result in performance degradation.

Therefore, when overriding the Equals method and the Hashcode method of a class, you should try to ensure that objects return true by equals, and that their hashcode return values are also equal.

Overriding the basic rules of hashcode
1 over equals return True Yes, their hashcode return value is also equal
2 the attribute used as the equals comparison standard in an object should be used to calculate the hashcode value.

When you add a Mutable object to HashSet, you must be very careful that if you modify an object in HashSet, it can cause the object to be equal to other objects in the collection, causing HashSet to be unable to access the object accurately.

The HashSet sub-object Linkedhashset maintains the element order using a linked list, keeping elements in the order of insertion, with performance slightly lower than hashset.

TreeSet class
TreeSet is the only implementation of the SortedSet interface to ensure that elements are sorted
TreeSet Common Methods Example:
Import Java.util.TreeSet;

public class Testtreeset {

/**
* @param args
*/
public static void Main (string[] args) {
TODO auto-generated Method Stub
TreeSet nums = new TreeSet ();
Add 4 integer objects to a TreeSet
Nums.add (5);
Nums.add (2);
Nums.add (10);
Nums.add (-9);
Output collection elements
System.out.println (Nums);
The first element in the output set
System.out.println (Nums.first ());
The last element in the output set
System.out.println (Nums.last ());
Returns a subset less than 4, not containing 4
System.out.println (Nums.headset (4));
Returns a subset greater than 5, containing 5
System.out.println (Nums.tailset (5));
Returns a subset greater than-3, less than 4
System.out.println (Nums.subset (-3, 4));
}

}


And HashSet set uses the hash algorithm to determine the location of the element storage, TreeSet collection uses the red and black tree data structure to order the elements, natural sorting and custom ordering of the two species, by default, the use of natural sorting.

When attempting to add an object to TreeSet, the object's class must implement the comparable interface, otherwise an exception occurs (when the first one is added and the second is added, an exception is thrown when TreeSet invokes the object's CompareTo (Object obj) method). Also, the objects added to TreeSet should belong to the same class, or an exception will be thrown.

Some common classes have implemented comparable interfaces, such as Bigdecimal,biginteger,character,boolean (True>false), string,date,time, etc.
For TreeSet, the criterion for judging the unequal of two objects is that the Equals method returns False, or the CompareTo method does not return 0, even if two objects are the same object and are treated as two objects. All when overriding the Equals method of a class that must be put into treeset, you should ensure that the results are consistent with the CompareTo method.

If a mutable object is added to TreeSet, and the subsequent program modifies the object's properties, causing it to change in size with other objects, the TreeSet does not adjust their order again, even causing the saved two objects to return true through equals. The CompareTo returns 0, and all the recommended HashSet and TreeSet collections are placed in immutable objects only.

Example:
Import Java.util.TreeSet;

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

/**
* @param args
*/
public static void Main (string[] args) {
TODO auto-generated Method Stub
TreeSet ts = new TreeSet ();
Ts.add (New R (5));
Ts.add (New R (-3));
Ts.add (New R (9));
Ts.add (New R (-2));
SYSTEM.OUT.PRINTLN (TS);
Take the first element out of the
R frist = (r) ts.first ();
Change its property value
Frist.count = 20;
Remove the last element
R last = (R) ts.last ();
Change its property value
Last.count =-2;
SYSTEM.OUT.PRINTLN (TS);
Failed to delete changed element
Ts.remove (New R (-2));
SYSTEM.OUT.PRINTLN (TS);
Remove unchanged element succeeded
Ts.remove (New R (5));
SYSTEM.OUT.PRINTLN (TS);
}

}

Enumset
Enumset is a collection designed specifically for enumeration classes, stored internally in a vector manner, with little memory and high efficiency
Enumset does not allow null elements to be added, otherwise an exception will occur
When attempting to copy an element from a collection collection to create a Enumset collection, you must ensure that all elements in the collection collection are enumerated values of the same enumeration class.
Example:
Import Java.util.EnumSet;

Enum season{
Spring,summer,fall,winter;
}

public class Enumsetdemo {

/**
* @param args
*/
public static void Main (string[] args) {
TODO auto-generated Method Stub
Enumset es1 = Enumset.allof (Season.class);
System.out.println (ES1);
Enumset es2 = enumset.noneof (Season.class);
System.out.println (ES2);
Es2.add (Season.winter);
Es2.add (season.spring);
System.out.println (ES2);
Output Summer,winter
Enumset Es3 = Enumset.of (Season.summer,season.winter);
System.out.println (ES3);
Output Summer,fall,winter
Enumset es4 = Enumset.range (Season.summer, Season.winter);
System.out.println (ES4);
Get the remainder of ES4
Enumset es5 = Enumset.complementof (ES4);
Output Spring
System.out.println (ES5);
}

}

Set of Java collections

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.