重写comparater比较器
TreeSet
能自动对对象进行排序,但是一般需要在类中重写比较方法
比较器介绍
在类中实现Comparable接口,并重写compareTo方法
排序对象类
package typing.overridecompare;
public class Person implements Comparable<Person>{
private String name;
private int age;
Person() {
}
Person(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return "[name:" + name + ",age:" + age + "]";
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public int compareTo(Person person) {
// 先以年龄进行排序,再以姓名长度进行排序
int num = this.getAge() - person.getAge();
if (num==0) {
num = this.getName().length() - person.getName().length();
}
return num;
}
}
创建TreeSet对象并添加Person对象自动排序
package typing.overridecompare;
import java.util.Random;
import java.util.TreeSet;
public class OverrideCompareTo {
private TreeSet<Integer> treeint;
private TreeSet<Person> treeperson;
public void treeInt() {
treeint = new TreeSet<Integer>();
Random r = new Random();
for (int i = 0; i < 10; i ++)
treeint.add(r.nextInt(100));
System.out.println(treeint);
}
public void treePerson() {
treeperson = new TreeSet<Person>();
treeperson.add(new Person("ali",20));
treeperson.add(new Person("aiya",16));
treeperson.add(new Person("bob", 16));
treeperson.add(new Person("boer", 21));
treeperson.add(new Person("lobo",15));
System.out.println(treeperson);
}
}
测试类
OverrideCompareTo compare = new OverrideCompareTo();
compare.treePerson();//输出结果:[[name:lobo,age:15], [name:bob,age:16], [name:aiya,age:16], [name:ali,age:20], [name:boer,age:21]]
自定义比较器,在比较器中实现,需要实现Comparator接口并重写compare方法
自定义比较器类
package typing.overridecompare;
import java.util.Comparator;
public class CharCompare implements Comparator<Character>{
@Override
public int compare(Character c1, Character c2) {
int num = c1 -c2;
if (num == 0)
num = 1;
return num;// 以字符串的ascll顺序进行排序
}
}
测试类
TreeSet<Character> charset = new TreeSet<Character>(new CharCompare());// 在声明TreeSet时传入自定义比较器对象
Scanner input = new Scanner(System.in);
String line = input.nextLine();
char[] arr = line.toCharArray();
for (char ch:arr)
charset.add(ch);
System.out.println(charset);
// 输入abbcba,输出aabbbc