Java container --- Set: HashSet & amp; TreeSet & amp; javashashset, --- sethashset

Source: Internet
Author: User
Tags set set

Java container --- Set: HashSet & TreeSet & LinkedHashSet, --- sethashset
1. Set interface Overview

SetDo not save repeated elements (how to determine if the elements are the same ?). If you try to add multiple instances of the same object to the Set, it will block this repetition. The most common use of Set is test normalization. You can easily ask whether an object is in a Set. Because of this, searching becomes the most important operation in the Set, so you usually chooseHashSetIt specifically optimizes the quick search.

Set has the same interface as Collection, so there is no additional function, unlike the previous List.In fact, Set is Collection., But the behavior is different. (This is a typical application of inheritance and Polymorphism: different behavior ).SetThe attribute is determined based on the object value.

Java. util Interface Set <E>
Parameter type E: the type of elements maintained by this set
All superclass interfaces: Collection <E>, Iterable <E>
All subclass interfaces: NavigableSet <E>, SortedSet <E>
All known implementation classes: AbstractSet, ConcurrentHashMap. KeySetView, ConcurrentSkipListSet, CopyOnWriteArraySet, EnumSet,HashSet, JobStateReasons,LinkedHashSet,TreeSet
2. Set common implementation class (1) HashSet

HashSetInherits the AbstractSet class and implements the Set, Cloneable, and Serializable interfaces. ByHash Table support(ActuallyHashMapInstance, based on

Implemented by HashMap. The underlying layer uses HashMap to store elements .), Is designedImproves search efficiency.

 
Constructor
All methods
(2) TreeSet

TreeSetInherits the AbstractSet class and implements the NavigableSet, Cloneable, and Serializable interfaces. Like HashSet, which is implemented based on HashMap,TreeSetIt is also based onTreeMap. BecauseTree,The most important feature of TreeSet is sorting, which provides ordered Set sets.

Parameter type
E-Types of elements maintained by this set
All Implemented Interfaces ( Implementation Interface):
Serializable, Cloneable, Iterable <E>, Collection <E>, NavigableSet <E>
Set <E> SortedSet <E>
Constructor
Common Methods

(3) LinkedHashSet

LinkedHashSetIntegrated with the linked list + hash tableHashCodeTo determine the storage location of the element.Linked ListMaintain the order of elements.

When traversing the set,LinkedHashSetThe elements of the set are accessed in the order of adding elements.

ForLinkedHashSetIt inherits fromHashSetAnd is based onLinkedHashMap.

Public class extends hashset <E> extends
HashSet<E> 
implements Set<E>,Cloneable,Serializable
Parameter type E-the type of elements maintained by this set
All Implemented Interfaces (Implementation Interface ):
Serializable, Cloneable, Iterable <E>, Collection <E>, Set <E>
Constructor
Methods (basically inherited methods)
3. set demo (1) HashSet
1 public class HashSetDemo {2 3/** 4 * @ param args 5 */6 public static void main (String [] args) {7 8 // 1, create a Set container object. 9 Set set = new HashSet (); // if it is generated as a HashSet, it can be sorted. 10 11 // 2. Add an element. 12 set. add ("abc"); 13 set. add ("nba"); 14 set. add ("heihei"); 15 set. add ("haha"); 16 set. add ("heihei"); 17 18 // 3, which can only be retrieved by the iterator. 19 for (Iterator it = set. iterator (); it. hasNext ();) {20 System. out. println (it. next (); 21} 22 23} 24 25} 26

(2)TreeSet 

1 public class TreeSetDemo2 {2 3/** 4 * @ param args 5 */6 public static void main (String [] args) {7 8 // initialize the TreeSet set to specify a comparator. 9 Set set = new TreeSet (new ComparatorByName (); 10 11 set. add (new Student ("xiaoqiang", 20); 12 set. add (new Student ("daniu", 24); 13 set. add (new Student ("xiaoming", 22); 14 set. add (new Student ("tudou", 18); 15 set. add (new Student ("daming", 22); 16 set. add (new Student ("dahuang", 19); 17 18 for (Iterator it = set. iterator (); it. hasNext ();) {19 Student stu = (Student) it. next (); 20 System. out. println (Stu. getName () + ":" + stu. getAge ()); 21} 22} 23 24} 25 /**///////////////////////////// //////////////////////////////////////// //////////////////////////////////////// /////// 26 * customize a comparator, sorts student objects by name. 27 * @ author Administrator 28*29 */30 public class ComparatorByName extends Object implements Comparator {31 32 @ Override 33 public int compare (Object o1, Object o2) {34 35 Student s1 = (Student) o1; 36 Student s2 = (Student) o2; 37 38 int temp = s1.getName (). compareTo (s2.getName (); 39 40 return temp = 0? S1.getAge ()-s2.getAge (): temp; 41} 42 43} 44 ////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// /// 45 public class Student implements Comparable {46 47 private String name; 48 private int age; 49 50 public Student () {51 super (); 52 53} 54 public Student (String name, int age) {55 super (); 56 this. name = name; 57 this. age = age; 58} 59 60 61 62/** 63 * overwrite the hashCode method. Defines the hash value based on the characteristics of the object. 64 */65 public int hashCode () {66 final int NUMBER = 37; 67 return name. hashCode () + age * NUMBER; 68} 69 70/** 71 * defines the basis for the same judgment content of the object. Overwrite the equals method. 72*73 */74 public boolean equals (Object obj) {75 76 if (this = obj) {77 return true; 78} 79 80 if (! (Obj instanceof Student) {81 throw new ClassCastException ("type error"); 82} 83 84 Student stu = (Student) obj; 85 86 return this. name. equals (stu. name) & this. age = stu. age; 87} 88 89 public String getName () {90 return name; 91} 92 public void setName (String name) {93 this. name = name; 94} 95 public int getAge () {96 return age; 97} 98 public void setAge (int age) {99 this. age = age; 100} 101 @ Ove Rride102 public String toString () {103 return "Student [name =" + name + ", age =" + age + "]"; 104} 105/** 106 * students have a comparison function. This function is used by natural sorting. 107 * sort the age in ascending order. 108 */109 @ Override110 public int compareTo (Object o) {111 112 Student stu = (Student) o; 113 // System. out. println (this. name + ":" + this. age + "........ "+ stu. name + ":" + stu. age); 114/* 115 if (this. age> stu. age) 116 return 1; 117 if (this. age <stu. age) 118 return-1; 119 return 0; 120 */121/* 122 * since the same name and age are the same person, it is considered as a duplicate element, there are two elements to be judged. 124 * since it is sorted by age. Therefore, determine the age first. When determining the name. 125 */126 int temp = this. age-stu. age; 127 128 return temp = 0? This. name. compareTo (stu. name): temp; 129 130} 131 132} 133

 

The content comes from API1.8, Java programming ideas, and Chuanzhi podcast courses.

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.