1. 程式人生 > >淺談Comparable與Comparator的區別

淺談Comparable與Comparator的區別

package com.list.customsort; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Set; import java.util.TreeSet; public class TestSort2 { public static void main(String[] args) { List<Person2> list = new
ArrayList<>(); list.add(new Person2("fd",20)); list.add(new Person2("chy",22)); list.add(new Person2("wgj",21)); System.out.println(list); Collections.sort(list,new Comparator<Person2>() { @Override public int compare(Person2 o1, Person2 o2) {
return o1.getAge().compareTo(o2.getAge()); } }); System.out.println(list); } } class Person2{ private String name; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; }
public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Person2(String name, Integer age) { super(); this.name = name; this.age = age; } @Override public String toString() { return "Person2 [name=" + name + ", age=" + age + "]"; } }