Crazy Java Learning Notes ($)-----------Set Set

Source: Internet
Author: User
Tags comparable set set

The set set is similar to a jar, thrown into "set", and there is no apparent order between objects in the collection.

The set set is essentially the same as the collection collection, and he does not provide any additional methods.

in fact set is collection, but the behavior is slightly different, set does not allow the inclusion of duplicate elements. allows an element that contains a value of null , but can have at most one null element.

Common methods

By definition, the Set interface inherits the Collection interface, all the original methods are ready-made, and no new methods are introduced. The specific Set implementation class relies on the Equals () method of the added object to check for equivalence.

Description of the function of each method:

public int size (): Returns the number of elements in the set, and returns Integer.max_value if the set contains more than integer.max_value elements;

public boolean IsEmpty (): Returns True if the set contains no elements;
Public Boolean contains (Object O): Returns True if the set contains the specified element;
Public Iterator Iterator (): Returns an iterator to the elements in the set, which returns no specific order unless set raises instances of certain classes of the guarantee;
Public boolean Add (Object O): Adds to set if the specified element does not exist in the set;
public boolean remove (Object o): Removes from set if the specified element exists in the set;
public boolean RemoveAll (Collection C): If the set contains the specified collection, all elements of the specified collection are removed from the set;
public void Clear (): Removes all elements from the set;

Principle Analysis

The order of HashSet elements is not related to the order in which they are added, while Linkedhashset preserves the order in which elements are added, and treeset sorts the elements in our set.


In general, TreeSet implementations are useful when you want to extract elements in an orderly manner from a collection. To be able to proceed smoothly, the elements that add treeset must be sortable. It is also necessary to implement comparable interface support for class objects added to TreeSet.

For the implementation of the comparable interface. Suppose a tree knows how to keep an orderly state of Java.lang wrapper class elements. In general, it is quicker to add elements to the HashSet and then convert the collection to TreeSet for an orderly traversal. This is very similar to the use of HashMap.


In fact, the implementation of the set principle is based on the map above. Many implementation classes in set are very similar to the use of some implementation classes in maps. "Key-value pairs" in the map, where "keys" cannot be duplicated. This and set elements can not be consistent, in fact, the set is used in the map "key" can not be repeated characteristics to achieve.

HashSet's ingenious implementation: is to create a "key-value pair", "key" is the object we want to deposit, "value" is a constant. This ensures that the information we need to store is "key". The "key" is not duplicated in the map, which ensures that all the elements we have in the set are not duplicated. The decision whether to add the element succeeds is by judging whether the "key-value pair" We have deposited with the map already exists, and if so, the return value must be constant: PRESENT, which indicates that the addition failed. If it does not exist, the return value is null to indicate that the addition succeeded.

Here is a test class

Settest.java

Package Com.haixu.set;import java.util.hashset;import java.util.set;/* * Set Set test! * */public class Settest {public static void main (string[] args) {  //hashset is a typical implementation of Set set<string> str1 = new Ha Shset<string> ();  Add a string Str1.add (new string ("You'll Succcess!"));  Add a String object again//Because two String objects compare equality//Add failures by means of the Equals method will return false Boolean result = Str1.add (new string ("Hold on haixu!")); SYSTEM.OUT.PRINTLN (Result + "------->" + str1); }}


HashSet class:

1. HashSet cannot store the same data as equals again . The reason is the same as equals, the data hash code is the same (Hashcode must be compatible with equals). A large amount of the same data will be stored in the linked list pointed to by the same hash cell, resulting in a serious hash conflict, which is disastrous for lookup efficiency.

2, HashSet storage is unordered, there is no relationship, he is not a set of linear structure.

3. Hashcode must be compatible with equals

When an element is deposited into the HashSet collection, Hsahset invokes the Hashcode method of the object to get the Hashcode value of the object, and then determines the hashcode position of the object based on the HashSet value.

If two elements return true through the Equals () method, but their Harbin code method return values are not equal, HashSet will store them in a different location!

This picture is worth a fortune! Read it well!

On the internet to find a lot of information are not detailed explanation of HashSet class, can only sum up!

Hashsettest.java

package com.haixu.set;/* * HashSet class practice, test object storage location * */import Java.util.hashset;class a{ public boolean equals (Object obj) {return true;}} Class B{public int hashcode () {return 1;}} Class C{public int hashcode () {return 2;} public boolean equals (Object obj) {return true;}} public class Hashsettest {public static void main (string[] args) {hashset<object> str1 = new Hashset<object> () Str1.add (New A ()), Str1.add (New A ()), Str1.add (new B ()), Str1.add (new B ()); Str1.add (new C ()); Str1.add (new C ()); System.out.println (STR1);}} 


Running results "[[email protected], [email protected],[email protected], [email protected],[ Email protected]]

Hashsettest2.java

Package Com.haixu.set;import java.util.hashset;import java.util.iterator;class r{int count;public R (int count) { This.count = Count;} Public String toString () {return "R[count:" + Count + "]";} public boolean equals (Object obj) {if (this = = obj) {return true;} if (obj! = null && obj.getclass () = = R.class) {R r = (r) obj;if (R.count = = This.count) {return true;}} return false;} public int hashcode () {return this.count;}} public class HashSetTest2 {public static void main (string[] args) {hashset<object> HS =new hashset<object> (); Hs.add (New R (5)), Hs.add (new R ( -3)), Hs.add (new R (9)), Hs.add (New R (-2));//Print HashSet collection, the collection element does not repeat SYSTEM.OUT.PRINTLN (HS) ;//Take out an element Iterator it = (Iterator) hs.iterator (); R first = (R) it.next ();//Assign a value of First.count = -3;//Output HashSet collection again, the collection has no duplicate element System.out.println (HS);// Delete the R object Hs.remove-3 (New R (-3));//Can be seen to be deleted class an object System.out.println (HS); SYSTEM.OUT.PRINTLN ("Does HS contain R objects with Count 3?") + Hs.contains (New R (-3))); SYSTEM.OUT.PRINTLN ("Does HS contain a R object with Count 5?") "+ Hs.contains (nEW R (5)));}} 



&NBSP; treeset principle:
   /*
 * treeset When storing objects, you can sort them, but you need to specify the algorithm for sorting
 * 
 * integer can be sorted (with default order), string can be sorted (in default order), exception occurs when custom class is stored (no order)
 * 
 * If you want to sort the objects of a custom class into TreeSet, you must implement the comparable interface
 *    Implement comparable
 *    override CompareTo () method on class
 *    Define a comparison algorithm within a method, return positive negative numbers or 0
 *    when using TreeSet storage objects, the Add () method will automatically call CompareTo () method to compare and store
 */

Based on comparison results using a two-tree form

TreeSet is to rely on treemap to achieve.
TreeSet is an ordered set, and the elements in the TreeSet are arranged in ascending order, by default, by natural ordering, meaning that the elements in treeset implement comparable interfaces. Or there is a custom comparer.
We can pass a comparer object that implements the comparator interface when constructing a TreeSet object.

Import Java.util.Iterator;
Import java.util.*;

public class Treesettest {
public static void Main (string[] args) {
Set ts = new TreeSet ();
Ts.add ("Haixu");
Ts.add ("Success");
Ts.add ("You can!");
Iterator it = Ts.iterator ();
while (It.hasnext ()) {
System.out.println (It.next ());
}
}
}

Output "Haixu, Success,you can!

The printed result is not the same as the order in which it was previously added, it is sorted by a single letter sorting method. This is because the string class implements the comparable interface.

If the object of a class that we define ourselves is to be added to the TreeSet, then this class must implement the comparable interface.

Comparator

You can pass a comparer when you use arrays to sort the elements in an array.

You can pass a comparer when you use collections to sort the elements in the collection.

Can you pass in a comparer when you use TreeSet to sort the elements that are added to them?

   Public Super E> Comparator) {        this (new treemap<e,object>(Comparator));    } 

By looking at how it is constructed, you know that you can pass in a comparer.

Enumsetis a private Set implementation that is used with the enumeration type. All elements in an enumeration set must come from a single enumeration type (that is, it must be the same type, and the type is a subclass of the enum).
An enumeration type is explicitly or implicitly specified when creating a set. The enumeration set is internally represented as a bit vector. This representation is very compact and efficient. This type of space and time performance should be very good,
Enough to be used as an alternative to the traditionally int-based "bit sign", with the advantage of high quality, type safety.
If the specified collection is also an enumeration set, the bulk operations (such as Containsall and Retainall) should also run very fast.
Iterators returned by the iterator method traverse these elements in their natural order, which is the order in which the enumeration constants are declared.
The returned iterator is weakly consistent: it never throws a concurrentmodificationexception, and does not necessarily show the effect of any set modifications that occur while the iteration is in progress.
Null elements are not allowed. Attempting to insert a null element will throw nullpointerexception. But
Attempting to test whether a null element appears or removes a null element will not throw an exception.
Like most collection, Enumset are out of sync. If multiple threads access an enumeration set at the same time,
And at least one thread modifies the set, the enumeration set should be synchronized externally. This is usually done by performing a synchronous operation on the object that naturally encapsulates the enumeration set.
If such an object does not exist, you should use the Collections.synchronizedset (Java.util.Set) method to "wrap" the Set.
It is best to do this at the time of creation to prevent unintended non-synchronous access:
set<myenum> s = Collections.synchronizedset (enumset.noneof (Foo.class));
Implementation considerations: All basic operations are performed within a fixed time period. Although not guaranteed, they are likely to be faster than their HashSet copies.
If the parameter is another Enumset instance, a bulk operation such as AddAll () and Abstractset.removeall (java.util.Collection)
will also be executed within a fixed time period.
Note 1: null elements are not allowed. Attempting to insert a null element will throw nullpointerexception. But
Attempting to test whether a null element appears or removes a null element will not throw an exception.
Note 2: The Enumset is not synchronized. is not thread-safe.
Note 3: The essence of Enumset is a set that is customized for an enumeration type, and all elements in the enumeration set must come from a single enumeration type.
Note 4: About Enumset storage, as mentioned in the documentation. “The enumeration set is internally represented as a bit vector. ”
I think it's supposed to be represented by a bit. Yu Zhi The corresponding enumeration variable is in the collection.
For example: 0x1001
If the convention starts at a low level, it represents a No. 0, and a third enumeration type variable in Enumset.
In this way, space and time performance should be very good.
Note 5: The position (ordinal) of enum constants for Enums can be obtained using the ordinal () method of the enum.
Note 6: An enumerated constant that can be an enumeration in the form of an array inside the JDK.
Here is an example from the Regularenumset.java in the JDK
private static <e extends enum<e>> e[] Getuniverse (class<e> elementtype) {
Return sharedsecrets.getjavalangaccess ()
. getenumconstantsshared (ElementType);
}
Note 7: The type of enumeration that an element belongs to must be explicitly or implicitly specified when the set is created.
Note 8 : For more knowledge of enum types, refer to enum type

Enumsetis a virtual class, we can only return it by the static method it providesEnumsetan instance of the implementation class. returns two different implementations of the Enumset: If the enumset size is less thanReturns the Regularenumset instance (which, of course, inherits from Enumset), which Enumset actually uses a long to store the Enumset. If the enumset size is greater than or equal to 64, the Jumboenumset instance is returned, which uses a long[] to store. The benefits of this are obvious: in most cases, the regularenumset efficiency is much higher than the jumboenumset.

Example 1import java.util.comparator;import java.util.enumset;import java.util.random;import Java.util.concurrent.synchronousqueue;import Java.util.concurrent.timeunit;public class Test {/** * @param args */PU  Blic static void Main (string[] args) {System.out.println ("enumset.noneof");   Enumset<student> set=enumset.noneof (Student.class);   Set.add (Student.harry);   Set.add (Student.robbie);  Set.add (Student.robin);  for (Student p:set) System.out.println (p);  Set.clear ();  System.out.println ("Enumset.allof");  Set=enumset.allof (Student.class);  for (Student p:set) System.out.println (p);  Set.clear ();  System.out.println ("Enumset.of One");  Set=enumset.of (Student.robin);  for (Student p:set) System.out.println (p);  System.out.println ("Enumset.of");  Set=enumset.of (Student.robin,student.harry); for (Student p:set) System.out.println (p); }}enum student{Robin ("Robin"), Harry ("Harry", "Max"), ROBBIE ("ROBBIE"); String name; int age; Private Student (String name) {this (name,0); } private Student (String Name,int age) {this.name=name; This.age=age;  } public String toString () {return name;}}


Crazy Java Learning Notes ($)-----------Set Set

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.