Comparable与Comparator
博客专区 > cpf2016 的博客 > 博客详情
Comparable与Comparator
cpf2016 发表于1年前
Comparable与Comparator
  • 发表于 1年前
  • 阅读 2
  • 收藏 0
  • 点赞 0
  • 评论 0

标题:腾讯云 新注册用户域名抢购1元起>>>   

(1)说明

                不管使用Comparator还是Comparable,在做比较的方法中:0表示相等,小于0表示排在前面,大于0表示排在后面(所以前面加上负号就可以逆序)

 

(2)Comparator(推荐使用)

           1.比较的类定义

                   可以看出没有任何处理

class Student{
	private long id;
	
	private String name;

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Student(long id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
}

           2.排序及测试

	@Test
	public void test() {
		List<Student> list = new ArrayList<Student>();
		
		Student student1 = new Student(1L, "ny");
		Student student2 = new Student(2L, "syx");
		Student student3 = new Student(3L, "ll");
		
		list.add(student1);
		list.add(student2);
		list.add(student3);
		
		Collections.sort(list, new Comparator<Student>() {
			@Override
			public int compare(Student o1, Student o2) {
				return (int) (o1.getId()-o2.getId());
			}
		});
		
		for (Student student : list) {
			System.out.println("id is "+student.getId()+";name is "+student.getName());
		}
	}

 

(3)Comparable

           1.比较的类定义

                   需要实现Comparable接口

class Student implements Comparable<Student>{
	private long id;
	
	private String name;

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Student(long id, String name) {
		super();
		this.id = id;
		this.name = name;
	}

	@Override
	public int compareTo(Student o) {
		return (int) (this.id-o.getId());
	}
}

           2.排序及测试

	@Test
	public void testComparable() {
		List<Student> list = new ArrayList<Student>();

		Student student1 = new Student(1L, "ny");
		Student student3 = new Student(3L, "ll");
		Student student2 = new Student(2L, "syx");

		list.add(student1);
		list.add(student2);
		list.add(student3);

		Collections.sort(list);

		for (Student student : list) {
			System.out.println("id is " + student.getId() + ";name is "
					+ student.getName());
		}
	}

            结果为:

id is 1;name is ny
id is 2;name is syx
id is 3;name is ll
 

 

共有 人打赏支持
粉丝 2
博文 3
码字总数 137812
×
cpf2016
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: