Java Learning Lesson 37th (Common Object API)-Collection Framework (v)-set collection: TreeSet collection

Source: Internet
Author: User
Tags comparable set set

First, Linkedhashset Collection

There are sub-classes under HashSet linkedhashset

API documentation for Linkedhashset explanation:

A hash table and a link list implementation of a Set interface with predictable iteration order. This implementation differs from HashSet in that the latter maintains a double-link list that runs on all items. This list of links defines the order of iterations, that is, the order in which the elements are inserted into the set ( Insert Order ). Note that the insertion order is not affected by The elements that are reinserted in the set. (If s.add (e)is called immediately after S.contains (e) returns true , the element e is reinserted into sets . )

This implementation allows the customer to avoid unspecified, HashSet often disorganized sequencing work, without incurring TreeSet associated cost increases

Import Java.util.hashset;import Java.util.iterator;import Java.util.linkedhashset;public class Main {public static void Main (string[] args) {//hashset hash = new HashSet (), unordered HashSet hash = new Linkedhashset (); Hash.add ("B"); Hash.add ("a") ; Hash.add ("C"); Hash.add ("D"); Iterator it = Hash.iterator (); while (It.hasnext ()) {System.out.println (It.next ())}}}

As above, with linkedhashset can achieve orderly storage, but there is no order is not important, the key is to ensure the only.


Second, TreeSet Collection


API documentation explains:

Based on TreeMap the NavigableSet implementation. Use the natural order of the elements to sort the elements, or sort based on what is provided when the set is created Comparator , depending on the construction method used.

This implementation add remove contains provides the guaranteed log (n) time overhead for basic operations (, and).

Note that if the interface is to be implemented correctly Set , the order in which the set is maintained (whether or not an explicit comparer is provided) must be consistent with equals .

The bottom line is that the TreeSet collection can sort the elements in the set set, fast, and out of sync

The storage of TreeSet is actually stored according to the storage characteristics of the binary tree (red and black tree), the left child is smaller than the father, the right child is greater than the father

Import Java.util.iterator;import Java.util.treeset;public class Main {public static void main (string[] args) {TreeSet tre E = new TreeSet (); Tree.add ("ad"); Tree.add ("abc"); Tree.add ("DSA"); Tree.add ("BCD"); Iterator it = Tree.iterator (); while (It.hasnext ()) {System.out.println (It.next ());}}}

Sorts the output according to the dictionary order.


TreeSet the only way to judge an element is if the return result of the comparison method is 0, yes, it is the same, not stored, regardless of the hashcode, equals.

Import Java.util.iterator;import Java.util.treeset;public class man/*extends object*/implements Comparable{private string Name;private int age;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;} Public Man () {super ();//TODO auto-generated constructor stub}public Man (String name, Int. age) {super (); this.name = Name;t His.age = age;} @Overridepublic int CompareTo (object arg0) {//object's natural sort//TODO auto-generated method stubif (! ( arg0 instanceof Man) throw new ClassCastException (); Man mans = (man) arg0;int te = this.age-man.age;//first ranked by age, then name return Te==0?this.name.compareto (man.name): TE;} public class Main {public static void main (string[] args) {TreeSet tree = new TreeSet () Tree.add (New Man ("ad")); Tree.add (New Man ("AC"), Tree.add ("SF"), Tree.add ("D", "one"), Tree.add (New Man ("ad", one)); Tree.add (New Man ("Ad", ()); Terator it = Tree.iterator (); while (It.hasnext ()) {MAn mans = (man) it.next (); System.out.println (Man.getname () + "::" +man.getage ());}}}

TreeSet how the elements are sorted one:

For the element to have a comparative function , it is necessary to implement the comparable interface, covering the CompareTo method


If the object does not have a natural sort, or has a natural sort but is not ordered in the way we need it

TreeSet the way the elements are sorted II (common development):

let the set itself have the comparison function, constructs a comparator , the replication compare method, To pass the class object as a parameter to the TreeSet constructor

Comparators are commonly used because they prevent some objects from being self-sufficient

Import Java.util.iterator;import Java.util.treeset;import Java.util.comparator;public class ComparatorRule Implements Comparator {//constructs a comparator based on the name of the man class @overridepublic int Compare (object arg0, Object arg1) {//TODO Auto-generated method Stubman man = (man) arg0; Man man2 = (man) arg1;int te = Man.getname (). CompareTo (Man2.getname ());//return 1; orderly, output, change the storage characteristics of two-fork tree return te==0? Man.getage ()-man2.getage (): TE;}} public class man/*extends object*/implements comparable{private string name;private int age;public string getName () {RET Urn name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;} Public Man () {super ();//TODO auto-generated constructor stub}public Man (String name, Int. age) {super (); this.name = Name;t His.age = age;} @Overridepublic int CompareTo (Object arg0) {//TODO auto-generated method stubif (!) arg0 instanceof Man) throw new ClassCastException (); Man mans = (man) arg0;int te = This.age-man.age;return te==0?this.name.compareto (man.name): TE;}} 

Iii. Practice: The application of comparators

To sort a string in length


Import Java.util.comparator;import Java.util.iterator;import Java.util.treeset;class ComparatorLengh implements Comparator{public int Compare (object arg0, Object arg1) {//TODO auto-generated method stubstring str0 = (String) arg0; String str1 = (string) arg1;int Te = Str0.length ()-str1.length (); return Te==0?str0.compareto (str1): TE;}} public class Main {public static void main (string[] args) {TreeSet tree = new TreeSet (new Comparatorlengh ()); Tree.add ("Ad" ); Tree.add ("ABSSC"); Tree.add ("dsafsd"); Tree.add ("BCD"); Tree.add ("B"); Iterator it = Tree.iterator (); while ( It.hasnext ()) {System.out.println (It.next ());}}}

Java Learning Lesson 37th (Common Object API)-Collection Framework (v)-set collection: TreeSet collection

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.