treesettest.java

来自「孙鑫JAVA从入门到精通配套练习程序。所有程序都实际运行过」· Java 代码 · 共 62 行

JAVA
62
字号
import java.util.*;
class TreeSetTest2
{
	public static void main(String[] args)
	{
		TreeSet ts = new TreeSet(new Student.StudentCmp());
		/*
		ts.add("winsun");
		ts.add("weixin");
		ts.add("mybole");
		*/
		ts.add(new Student(2, "zhangshan"));
		ts.add(new Student(1, "wangwu"));
		ts.add(new Student(3, "lisi"));
		ts.add(new Student(2, "mybole"));
		
		Iterator it = ts.iterator();
		while(it.hasNext())
		{
			System.out.println(it.next());
		}
	}
}

class Student implements Comparable
{
	int num;
	String name;
	Student(int num, String name)
	{
		this.num = num;
		this.name = name;
	}
	public String toString()
	{
		return num + ": " + name;
	}
	static class StudentCmp implements Comparator
	{
		public int compare(Object o1, Object o2)
		{
			int result;
			Student s1 = (Student)o1;
			Student s2 = (Student)o2;
			result = s1.num > s2.num ? 1 : (s1.num == s2.num ? 0 : -1);
			if (0 == result)
			{
				result = s1.name.compareTo(s2.name);
			}
			System.out.println("using Comparator!");
			return result;
		}
	}
	public int compareTo(Object o)
	{
		int result;
		Student s = (Student)o;
		result = num > s.num ? 1 : (num == s.num ? 0 : -1);
		return result;
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?