java_泛型 TreeSet 判断hashcode/length(升序排列)

package ming;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
/*
 * 按照hashcode或者length排列
 * 以升序排列
 * 实现TreeSet
 * */

class A11 implements Comparator<Object> {

	@Override
	//Object为String父类,符合要求
	public int compare(Object fst, Object snd) {
		return hashCode() > snd.hashCode() ? 1
				: hashCode() < snd.hashCode() ? -1 : 0;
	}

}

public class GenericMethodTest {
	public static void main(String[] args) {
		TreeSet<String> ts1 = new TreeSet<String>(new A11());

		ts1.add("hello");
		ts1.add("wa");

		TreeSet<String> ts2 = new TreeSet<String>(new Comparator<String>() {
			public int compare(String fst, String snd) {
				return fst.length() > snd.length() ? -1
						: fst.length() < snd.length() ? 1 : 0;
			}
		});
		ts2.add("hello");
		ts2.add("wa");
		ts2.add("one");
		System.out.println(ts1);
		System.out.println(ts2);
	}
}


原文地址:https://www.cnblogs.com/MarchThree/p/3720457.html