Java Collection Framework-treeset exercises

Source: Internet
Author: User

Import java.util.*;/* Exercise: Sort by string length. The string itself is comparable, but the way it is compared is not required.      At this point, you can only use the comparator note: in mode two: int num=new integer (str1.length ()). CompareTo (New Integer (Str2.length ())); There are three possible values for NUM at this time. Positive, negative, zero. Never write the following code: if (num==1) return 1;num does not necessarily equal 1. The 0,1,-1 we return in the function represents only three cases: 0, positive, negative. This must be noted. */class Mycompare implements Comparator//Custom Comparator {public int compare (Object obj1,object obj2) {if (! ( Obj1 instanceof String) | | ! (Obj2 instanceof String)) throw new RuntimeException ("Not a string! "); String str1= (String) obj1; String str2= (String) obj2;/* way One if (Str1.length () >str2.length ()) Return 1;if (Str1.length () ==str2.length ()) {return Str1.compareto (STR2);} return-1;*//* mode two */int num=new integer (Str1.length ()). CompareTo (New Integer (Str2.length ())); if (num==0) {return Str1.compareto (STR2);} return num;}} If there is no custom class above, then the TreeSet will be sorted in natural order (the letter of the string is naturally sorted) class TreeSetTest1 {public static void main (string[] args) {TreeSet ts= New TreeSet (New Mycompare ()),//treeset ts=new TreeSet (), Ts.add ("ABCD"), Ts.add ("DGF"); Ts.add ("Aakuop"); Ts.add ("Po") ; ts.add("Hello"), Ts.add ("Hello"), Ts.add ("World"), Ts.add ("Werttif"); Ts.add ("Hello"); Iterator It=ts.iterator (); while ( It.hasnext ()) {SOP ((String) It.next ());}} public static void Sop (Object obj) {System.out.println (obj);}}

Java Collection Framework-treeset exercises

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.