自定义排序

1、TreeSet实现自定义排序规则

class Person {
	String name;
	int score;

	public Person(String name, int score) {
		this.name = name;
		this.score = score;
	}
}

class PersonComparator implements Comparator {
	public int compare(Object o1, Object o2) {
		Person p1 = (Person) o1;
		Person p2 = (Person) o2;
//		return p1.score - p2.score;
		return p1.name.compareTo(p2.name);
	}
}

public class myls {
	// TreeSet排序规则Comparator案例
	public static void main(String[] args) {
		TreeSet<Person> set = new TreeSet<Person>(new PersonComparator());
		set.add(new Person("c", 80));
		set.add(new Person("b", 70));
		set.add(new Person("a", 60));
		set.add(new Person("d", 75));
		
		Iterator<Person> ite = set.iterator();
		while (ite.hasNext()) {
			Person p = (Person) ite.next();
			System.out.println(p.name + ":" + p.score);
		}
	}
}


发布了131 篇原创文章 · 获赞 79 · 访问量 31万+

猜你喜欢

转载自blog.csdn.net/qq_31780525/article/details/78808004