Comparison principle of different data structures

Source: Internet
Author: User

The comparison principle of determining whether elements are identical in different data structures arraylist   equalshashset    hashcode   equalstreeset     the return 0  of the compare of the custom comparator or the CompareTo of the element itself rutren  0treeset look at the following example Class treesetdemo3 {public static void main (String[] args)  { Treeset ts = new treeset (New studentcomparatorbyname ());//Comparator          //treeset ts = new treeset ();//element itself Ts.add (new Student ("Lisi0" ), Ts.add (New student ("Lisixx")), Ts.add (New student ("Lisi9")), Ts.add (New student (" Lisi8, Ts.add (new student ("Lisixx"), Ts.add (New student ("Lisi4");//ts.add (new  Student (Ts.add)); (New student ("Lisi7", 27)); SYSTEM.OUT.PRINTLN (TS);}} Class studentcomparatorbyname implements comparator{public int compare (Object o1 , Object o2) {student s1 =  (Student) O1; Student s2 =  (Student) O2;int num = s1.getname (). CompareTo (S2.getname ()); return num==0?new  integer (S1.getage ()). CompareTo (New integer (S2.getage ())): num;}} Students of the same age are regarded as the same student. Sort by the age of the students. class student implements comparable{private int age;private string name; Student (string name,int age) {this.age = age;this.name = name;} Public int compareto (object obj) {student stu =  (Student) obj;int num =  new integer (this.age). CompareTo (New integer (stu.age)); Return num==0?this.name.compareto ( Stu.name): Num;/*if (this.age>stu.age) return 1;if (this.age==stu.age) Return this.name.compareto ( Stu.name); Return -1;*//**/}public int getage () {return age;} Public string getname () {return name;} Public string tostring () {return name+ "::" +age;}}

How the different data structures compare

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.