Java SE treeset implement comparator interface yourself

Source: Internet
Author: User
Tags java se
1-Letter Comparator Implementation method code in reverse order
Import Java.util.Comparator;
Import Java.util.Iterator;
Import Java.util.TreeSet;


public class TreeSetTest3 {public
	static void Main (string[] args) {
		TreeSet set = new TreeSet (new Mycomparator ()) ;
		
		Set.add ("C");
		Set.add ("A");
		Set.add ("B");
		Set.add ("E");
		Set.add ("F");
		Set.add ("D");
		
		for (Iterator iter = Set.iterator (); Iter.hasnext ();) {
			String value = (string) iter.next ();
			System.out.println (value);

}}  Class Mycomparator implements comparator{
	@Override public
	int Compare (object O1, Object O2) {
		String S1 = (String) O1;
		String s2 = (string) O2;
		Return S2.compareto (S1);
	}


2 people in ascending order to achieve the comparator interface method, the source code is as follows
Import Java.util.Comparator;
Import Java.util.TreeSet;


public class TreeSetTest2 {public
	static void Main (string[] args) {
		
		TreeSet set = new TreeSet (New Mycomparator2 () );
		
		person P1 = new person (a);
		person P2 = new person (a);
		Person P3 = new person (a);
		person P4 = new person (n);
		
		Set.add (p1);
		Set.add (p2);
		Set.add (p3);
		Set.add (p4);
		
		SYSTEM.OUT.PRINTLN (set);
	}

Class person{
	
	int score;
	Public person (int score) {
		this.score = score;
	}
	
	@Override public
	String toString () {return
		string.valueof (this.score);
	}
}

Class Mycomparator2 implements comparator{
	@Override public
	int Compare (object O1, Object O2) {person
		
		p1 = (person) O1;
		person P2 = (person) O2;
		if (P1.score>p2.score) {return
			1;
		}
		if (P1.score==p2.score) {return
			0;
		}
		Return-1
	}
}

3 This uses a policy pattern.
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.