Java Foundation _set Collection

Source: Internet
Author: User
Tags comparable set set


Set Set


1. Overview
Collection
List collection: Sequential (consistent in order of storage and extraction), repeatable.
Set set: unordered (storage order and check out inconsistencies), unique

2.HashSet
(1). Overview: HashSet does not guarantee the set iteration order, as an implementation of the set () that inherits the parent class interface, where the elements are unique.

(2). Why HashSet storage does not guarantee its uniqueness
By looking at the source code of the Add () method, we know that this method relies on two methods: Hashcode () and Equals ().

Steps to add:
First, compare the hash value
If same, go ahead, compare the address value or go to equals ()
If different, add directly to the collection

Follow the steps of the method:
First look at whether the hashcode () value is the same
Same: Continue to the Equals () method
Returns true: Indicates that the element is duplicated and does not add
Returns false: The description element is not duplicated and is added
Not the same: add elements directly to the collection
If the class does not override both methods, the default is to refer to the method inside the object (), which is generally the same, and the string class overrides the Hashcode () and Equals () methods, so
It will remove the same string of content, leaving only one.

Code:
public class Test {
public static void Main (string[] args) {
Hashset<string> hs=new hashset<string> ();
Hs.add ("Hello");
Hs.add ("World");
Hs.add ("Java");
Hs.add ("World");
for (String s:hs) {
System.out.println (s);
}
}
}
Output results
World
Java
Hello


3.LinkedHashSet class

(1). Linkedhashset: The underlying data structure consists of a hash table and a linked list.
The hash table guarantees the uniqueness of the data.
The chain list guarantees the order of the elements. (removed to be consistent with storage)

(2). Code implementation
public class Test {
public static void Main (string[] args) {
Linkedhashset<string> hshashset=new linkedhashset<string> ();
Hshashset.add ("Hello");
Hshashset.add ("World");
Hshashset.add ("Java");
Hshashset.add ("World");
Hshashset.add ("Java");
for (String S:hshashset) {
System.out.println (s);
}
}
}
Output Result:
Hello
World
Java

4.TreeSet class

(1). The TreeSet class is able to sort elements by one rule, and the element is unique.

(2). Sort the two ways:
Natural sort
Comparator sorting (force sorting of the whole)


(3). TreeSet class stores custom objects (custom sort)

A: You didn't tell us how to sort it?
Sort by age size
B: Element What's the only thing you didn't tell me?
The same element is assumed to be the same as the member variable value
C: What do I need to do to achieve a custom sort?
Show natural Sort interface: comparable
Rewrite CompareTo () {
}

Code implementation
Student class:
public class Student implements comparable<student>{
Student Name
private String name;
Age
private int age;

No reference
Public Student () {

}
With parametric construction
Public Student (int age, String name) {
Super ();
This.age=age;
This.name=name;
}
Public String GetName () {
return name;
}

public void SetName (String name) {
THIS.name = name;
}
public int getage () {
return age;
}
public void Setage (int.) {
This.age = age;
}
@Override
public int CompareTo (Student s) {
Compare age, order in size
int num=this.age-s.age;
Whether the age is true or not, and see if the names of the two are equal
int Num2=num==0?this.name.compareto (s.name): num;
Meet two conditions before returning
return num2;
}
}
Test class
public class Test {
public static void Main (string[] args) {
Treeset<student> tsset=new treeset<student> ();
Student s1=new Student (12, "fat");
Student s2=new Student (12, "fat");
Student s3=new Student (13, "skinny");
Student s4=new Student (14, "Zhang San");
Student s5=new Student (15, "John Doe");
Tsset.add (S1);
Tsset.add (S2);
Tsset.add (S3);
Tsset.add (S4);
Tsset.add (S5);

for (Student S:tsset) {
System.out.println (S.getname () + "----" +s.getage ());
}
}
}
Output results
Fat----12
Skinny----13
Zhang San----14
John Doe----15

Description
@Override
public int CompareTo (Student arg0) {
TODO auto-generated Method Stub
return 0;
return 1;
return-1;
}
Return 0: Indicates that when stored, each one is the same as the root node, and only one element is stored.
Return 1: This indicates that each element is larger than the root node at the time of storage, which indicates the use of nodes.
What is generally needed to return, this one is what we need to customize.


(4). TreeSet Comparator sorting

A: Natural ordering (the elements have their own comparative), sorted by the element's own characteristics
Let the element attribute class implement the natural sort interface comparable

B: Comparator sort (set with comparison), with set internal decision ordering
Let the constructor of the collection parent accept the subclass object of a comparer comparator


Code implementation
customizing external classes
public class Mycomparator implements comparator<student>{

@Override
public int Compare (Student s1, Student S2) {
Compare the two objects that were passed over
Compare name length
int Num=s1.getname (). Length ()-s2.getname (). Length ();
Compare name Content
int Num1=num==0?s1.getname (). CompareTo (S2.getname ()): num;
Compare age
int Num2=num1==0?s1.getage ()-s2.getage (): NUM1;
return num2;
}
}
Student class
public class Student {
Student Name
private String name;
Age
private int age;

No reference
Public Student () {

}
With parametric construction
Public Student (int age, String name) {
Super ();
This.age=age;
This.name=name;
}
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
public int getage () {
return age;
}
public void Setage (int.) {
This.age = age;
}
}
Test class
public class Test {
public static void Main (string[] args) {
Using an external class, you can also use an anonymous inner class
Treeset<student> tsset=new treeset<student> (New Mycomparator ());
Student s1=new Student (12, "fat 1");
Student s2=new Student (12, "fat 1");
Student s3=new Student (13, "skinny");
Student s4=new Student (14, "Zhang San");
Student s5=new Student (15, "King two Leper");
Tsset.add (S1);
Tsset.add (S2);
Tsset.add (S3);
Tsset.add (S4);
Tsset.add (S5);
for (Student S:tsset) {
System.out.println (S.getname () + "----" +s.getage ());
}
}
}
Output Result:
Zhang San----14
Skinny----13
Fat 1----12
Wang er flaxseed----15

Use anonymous inner class code as follows, this time does not need to define an external class (in fact, it is a different method implementation):
public class Test {
public static void Main (string[] args) {
Using an external class method, the notification can also use anonymous inner classes
Treeset<student> tsset=new treeset<student> (New comparator<student> () {
@Override
public int Compare (Student s1, Student S2) {
Compare the two objects that were passed over
Compare name length
int Num=s1.getname (). Length ()-s2.getname (). Length ();
Compare name Content
int Num1=num==0?s1.getname (). CompareTo (S2.getname ()): num;
Compare age
int Num2=num1==0?s1.getage ()-s2.getage (): NUM1;
return num2;
}
});
Student s1=new Student (12, "fat 1");
Student s2=new Student (12, "fat 1");
Student s3=new Student (13, "skinny");
Student s4=new Student (14, "Zhang San");
Student s5=new Student (15, "King two Leper");
Tsset.add (S1);
Tsset.add (S2);
Tsset.add (S3);
Tsset.add (S4);
Tsset.add (S5);

for (Student S:tsset) {
System.out.println (S.getname () + "----" +s.getage ());
}

}
}

Java Foundation _set Collection

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.