A detailed explanation of the Java set set __java

Source: Internet
Author: User
Tags comparable repetition set set
One, Set set: Focus on the unique nature of the system set to know whether something is close to the collection and does not store duplicate elements

Used to store elements that are unordered (not necessarily the same in the order in which they are stored and fetched), and values cannot be duplicated.

Equality of objects

Two references to the same object on the heap are equal. If you call the Hashcode method on two references, you get the same result, and if the class that the object belongs to does not overwrite the Hashcode method of object, Hashcode returns the ordinal number that is unique to each object (which is computed by the memory address of the object). Therefore the hashcode values of two different objects cannot be equal.

If you want two different person objects to be considered equal, you must override the Hashcode method and the Equals method of object, because the object Hashcode method returns the memory address of the objects, so you must override the Hashcode method. To ensure that two different objects have the same hashcode, and that you need two different objects to compare the Equals method returns True

There are no unique methods in the collection that inherit directly from the collection.

---| Itreable      interface implements this interface to use the enhanced for loop
				---| Collection		interface to describe all set commonalities
					---| The list interface	    can have a collection of repeating elements
                            ---| ArrayList   
                            ---|  LinkedList
					---| Set interface	    can not have a collection of duplicate elements

Case: The Set collection adds elements and uses iterators to iterate through the elements.

The public class Demo4 {public
	static void Main (string[] args) {
		//set collection is inconsistent in the order in which they are stored and fetched.
		Set hs = new HashSet ();
		Hs.add ("World Military");
		Hs.add ("Weapon knowledge");
		Hs.add ("Ship Knowledge");
		Hs.add ("Han and Defense");
		SYSTEM.OUT.PRINTLN (HS);
		[Ship knowledge, world military, weapon knowledge, Han and defense]
		Iterator it = Hs.iterator ();
		while (It.hasnext ()) {
			System.out.println (It.next ());
		}
}}
Second, HashSet

---| Itreable      interface implements this interface to use the enhanced for loop
				---| Collection		interface to describe all set commonalities
					---| The list interface	    can have a collection of repeating elements
                            ---| ArrayList   
                            ---|  LinkedList
					---| Set interfaces	    may not have a collection of repeating elements
                            ---|  The hashset thread is unsafe and has a fast access rate. The bottom layer is implemented as a hash table.

HashSet

Hash values are stored on the side of the hash table. The order of the HashSet storage elements is not stored in the order in which they were saved (and the list is obviously different), so the data is obtained by the hash value.

HashSet rules that do not deposit duplicate elements. Using Hashcode and equals

Because set collections are collections that cannot be stored in duplicate elements. So HashSet also has this characteristic. HashSet How to check for duplicates. HashSet will judge whether the element is duplicated by the element's Hashcode () and the Equals method.

When you try to add an object to the HashSet, HashSet uses the hashcode of the object to determine where the object is joined. It is also compared with the hashcode of other objects that have already been added, assuming that the object does not recur if there is no equal hashcode,hashset.

Simply put, if the object's Hashcode value is different, then HashSet will assume that the object is not equal.

So when we customize a class, we need to rewrite hashcode to make sure that the object has the same hashcode value.

If the hashcode value of an element (object) is the same, can it be stored in the hashset? Of course not, you will continue to use equals for comparison. If the Equals is True then HashSet thinks the newly joined object repeats, so the join fails. If the Equals is False then HashSet thinks the newly added object is not duplicated. The new element can be saved.

Summarize:

The hash value of the element is obtained by the Hashcode method of the element, HashSet first to determine the hash value of the two elements, and then compare the Equals method if the equls result is true, HashSet is treated as the same element. If Equals is false, it is not the same element.

How elements that have the same hash value equal to False are stored, and are deferred under the same hash value (elements that can be considered to have the same hash value are placed in a hash bucket). That is, the hash-like deposit of a column.

Hashtable


Figure 1:hashcode values are not the same

Figure 2:hashcode values are the same, but equals are not the same.

HashSet: Determines the position of an element in memory by Hashcode value. Multiple elements can be stored in a hashcode position.

When the hashcode () value equals () returns to True, the HashSet collection considers the two elements to be the same element. Store only one (repeating element cannot be placed). Call principle: First judge the value of the Hashcode method, if the same will be judged equals if not the same, will not call the Equals method.

HashSet exactly how to judge two elements of repetition.

By Hashcode the method and the Equals method to guarantee the uniqueness of the element, add () returns a Boolean type

To determine whether two elements are the same, first to determine whether the hashcode value of the element is consistent, only if the value is consistent, the Equals method is judged, if the value of the two objects stored in the HashSet is the same as the result of the same Equals method returns True. So hashset that these two elements are the same element and store only one (repeating elements cannot be saved).

Note: The HashSet set determines the Hashcode method before determining whether the element is the same, and if the same will determine equals. If it is not the same, the Equals method is not invoked.

HashSet and ArrayList collections have methods that determine whether elements are the same.

Boolean contains (Object o)

HashSet using the Hashcode and Equals method, ArrayList uses the Equals method

Case:

Use HashSet to store strings and try to add duplicate strings

Review the Equals (), Hashcode () Two methods of the string class.

The public class Demo4 {public
	static void Main (string[] args) {
		//Set collection is not in the same order as it was stored and fetched.
		Set hs = new HashSet ();
		Hs.add ("World Military");
		Hs.add ("Weapon knowledge");
		Hs.add ("Ship Knowledge");
		Hs.add ("Han and Defense");

		Returns the number of elements in this set
		System.out.println (Hs.size ());//4

		//If this set does not already contain the specified element, return True
		boolean add = Hs.add ("World Army Matter "); False
		System.out.println (add);

		Returns the number of elements in this set
		System.out.println (Hs.size ());//4
		iterator it = Hs.iterator ();
		while (It.hasnext ()) {
			System.out.println (It.next ());
		}
}}

Use HashSet to store custom objects and try to add duplicate objects (duplicate judgments of objects)

public class Demo4 {public static void main (string[] args) {hashset hs = new HashSet ();
		Hs.add (New person ("Jack", 20));
		Hs.add (New person ("Rose", 20);
		Hs.add (New person ("hmm", 20));
		Hs.add (New person ("Lilei", 20));

		Hs.add (New person ("Jack", 20));
		Iterator it = Hs.iterator ();
			while (It.hasnext ()) {Object next = It.next ();
		System.out.println (next);
	Class Person {private String name;

	private int age;
		Person () {} public person (String name, int age) {this.name = name;
	This.age = age;
	Public String GetName () {return name;
	public void SetName (String name) {this.name = name;
	public int getage () {return age;
	public void Setage (int age) {this.age = age;
		@Override public int hashcode () {System.out.println ("hashcode:" + this.name);
	return This.name.hashCode () + age * 37;
		@Override public boolean equals (Object obj) {System.out.println (this +---equals---+ obj); if (obj instanceof person) {
			Person P = (person) obj;
		Return This.name.equals (p.name) && this.age = = P.age;
		else {return false;
	@Override public String toString () {return "Person@name:" + THIS.name + "Age:" + this.age; }

}

Problem: There is now a batch of data that requires that storage elements not be duplicated and sorted. ArrayList, LinkedList cannot remove duplicate data. HashSet can remove repetition, but it is unordered.

So we're going to use TreeSet.

Three, TreeSet

Case: Storing string elements using the TreeSet collection and traversing

public class Demo5 {public
	static void Main (string[] args) {
		TreeSet ts = new TreeSet ();
		Ts.add ("CCC");
		Ts.add ("AAA");
		Ts.add ("ddd");
		Ts.add ("BBB");

		SYSTEM.OUT.PRINTLN (TS); [AAA, BBB, CCC, DDD]

	}
}
---| Itreable      interface implements this interface to use the enhanced for loop
				---| Collection		interface to describe all set commonalities
					---| The list interface is	    ordered and can be duplicated, with a set of angular marks
                            ---| ArrayList   
                            ---|  LinkedList
					---| Set interfaces	    are unordered and cannot be duplicated
                            ---|  The hashset thread is unsafe and has a fast access rate. The bottom layer is implemented as a hash table.
                            ---| TreeSet  Red-Haishi data structure, by default, the element is naturally sorted (String). If two objects return a value of 0 at the time of comparison, the elements are duplicated.

Red-Haishi

A red-black tree is a specific type of two-prong tree

Red-Black Tree algorithm rules: The left small right large.

Since treeset can be sorted naturally, treeset must have a sort rule.

1: Allow the saved element to customize the comparison rule.

2: Specify the collation for TreeSet.

Mode one: The elements themselves have a comparative

The element itself has the comparison, needs the element realization comparable interface, the rewriting CompareTo method, namely lets the element own comparison, this way called the element natural sort also is called the default sort.

Mode two: The container has the comparative sex

When the elements themselves do not have a comparative, or their own comparative is not needed. So at this time you can let the container itself. You need to define a class to implement the interface comparator, rewrite the Compare method, and pass the subclass instance object of the interface as a parameter to the TreeMap collection's construction method.

Note: When the comparable comparison mode and the comparator comparison mode exist at the same time, the comparator comparison mode is the main;

Note: When overriding the CompareTo or compare methods, you must compare the minor conditions when you explicitly compare the primary conditions for equality. (assuming that the name and age of people are the same, if you want to sort people by age, if the age of the same person, how to deal with.) You cannot return 0 directly, because you may have different names (people of different ages with the same name). In this case, you need to make a minor conditional judgment (you need to judge the name), only the name and age equal to return 0.

Determine uniqueness by return 0来.

Question: Why is the string default output sorted in ascending order using TreeSet? Because the string implements an interface called the comparable interface. The string overrides the CompareTo method of the interface, so the string object has a comparative nature. My custom elements (such as the Person class, book Class) want to be stored in the TreeSet collection, you need to implement the interface, that is, to make the custom objects have the comparability.

The elements that are stored in the TreeSet collection have a comparative nature.

Comparison to implement the comparable interface, rewrite the CompareTo method of the interface

TreeSet belongs to the set set, and the elements of the collection cannot be duplicated, treeset how to guarantee the uniqueness of the element

The uniqueness of the element is guaranteed by means of CompareTo or compare methods.

The added element must implement the comparable interface. When the CompareTo () function returns a value of 0 o'clock, the two objects are equal, and the object is not added in.

Comparator interface

----| The comparable
       		compareTo (Object o)     element itself has a comparative
----| Comparator
       		Compare (Object O1, Object O2)	pass the comparer to the container

TreeSet sets are sorted in two ways:

First, let the elements themselves have a comparative nature.

That is, the element needs to implement the comparable interface, overwriting the CompareTo method.

This approach is also a natural sort of element, or it can be called a default sort.

Age according to search conditions, the same age and more than the name.

public class Demo4 {public static void main (string[] args) {TreeSet ts = new TreeSet ();
		Ts.add (New person ("AA", 20, "male"));
		Ts.add (New person ("BB", 18, "female"));
		Ts.add (New person ("CC", 17, "male"));
		Ts.add (New person ("DD", 17, "female"));
		Ts.add (New person ("DD", 15, "female"));


		Ts.add (New person ("DD", 15, "female"));
		SYSTEM.OUT.PRINTLN (TS); System.out.println (Ts.size ());
	5} class person implements comparable {private String name;
	private int age;

	Private String gender;
		Public person () {} public person (string name, int age, string gender) {this.name = name;
		This.age = age;
	This.gender = gender;
	Public String GetName () {return name;
	public void SetName (String name) {this.name = name;
	public int getage () {return age;
	public void Setage (int age) {this.age = age;
	Public String Getgender () {return gender;
	} public void Setgender (String gender) {This.gender = gender; @Override public int hashcode () {return NAMe.hashcode () + age * 37;
		public boolean equals (Object obj) {System.err.println (this + equals: + obj); if (!) (
		obj instanceof person)} {return false;
		Person P = (person) obj;

	Return This.name.equals (p.name) && this.age = = P.age;
	Public String toString () {return ' person [name= ' + name +], age= "+ Age +", gender= "+ gender +"];
		@Override public int compareTo (Object obj) {person p = (person) obj;
		System.out.println (this+ "compareTo:" +p);
		if (This.age > P.age) {return 1;
		} if (This.age < p.age) {return-1;
	Return This.name.compareTo (P.name); }

}

Second, let the container itself have a comparative, custom comparator.

Requirements: When the elements themselves do not have a comparative, or the elements themselves have the comparative is not required.

Then only allow the container itself.

Defines a class that implements the comparator interface and overrides the Compare method.

and passes the subclass object of the interface as a parameter to the constructor of the TreeSet collection.

When comparable comparison mode, and comparator comparison mode exist at the same time, to comparator

Comparison mode is the main.

public class Demo5 {public static void main (string[] args) {TreeSet ts = new TreeSet (new Mycomparator ());
		Ts.add ("The New book" ("I-AM", 100);
		Ts.add (new book ("Java Core technology", 75));
		Ts.add (new book ("Modern Operating System", 50));
		Ts.add (new book ("Java Employment Tutorial", 35));
		Ts.add ("The New book" ("I-AM", 100);

		Ts.add (New book ("CCC in Java", 100)); 
	SYSTEM.OUT.PRINTLN (TS);
		The class Mycomparator implements Comparator {public int compare (object O1, Object O2) {Book B1 = (book) O1;
		Book b2 = (book) O2;
		System.out.println (b1+ "Comparator" +b2);
		if (B1.getprice () > B2.getprice ()) {return 1;
		} if (B1.getprice () < B2.getprice ()) {return-1;
	Return B1.getname (). CompareTo (B2.getname ());
	Class Book {private String name;

	private double price;
	Public book () {} public String GetName () {return name;
	public void SetName (String name) {this.name = name;
	Public double GetPrice () {return price;
public void Setprice (double) {		This.price = Price;
		Public book (String name, double price) {this.name = name;
	This.price = Price;
	@Override public String toString () {return ' book [name= ' + name + ', price= ' + price +] '; }

}


Four, Linkedhashset

The order in which the inserts will be saved.

When you see an array, you must think of a corner mark.

When you see link, you must think of first,last.

When you see a hash, you want to think of hashcode,equals.

When you see a tree, you must think of two interfaces. Comparable,comparator.

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.