一、容器类List和Map实现Collection接口。但是,和Collection接口类似的,还有Collections类,Collections类提供方法实现容器类的排序、打乱顺序、复制、取最大值、取最小值、反转等功能。
二、规范化自定义类
1、使用Collections.sort(list);可以对list储存的对象进行排序。但是对于自定义的对象,却无法进行排序,因为使用该方法排序需要自定义类实现Comparable<T>接口,并重写compareTo方法。
二、规范化自定义类
1、使用Collections.sort(list);可以对list储存的对象进行排序。但是对于自定义的对象,却无法进行排序,因为使用该方法排序需要自定义类实现Comparable<T>接口,并重写compareTo方法。
class Person implements Comparable<Person>{
private String name="";
private double score=0.0;
public Person(String name,double score){
this.name=name;
this.score=score;
}
@Override
public int compareTo(Person o) {
// TODO Auto-generated method stub
return (int)(this.score-o.score);
}
}
2、Java中数组或者ArrayList等容器类可以使用toString()方法输出存储内容,但是自定义类要使用该方法,需要重写toString()方法。
class Person implements Comparable<Person>{
private String name="";
private double score=0.0;
public Person(String name,double score){
this.name=name;
this.score=score;
}
public String getName(){
return this.name;
}
public String toString(){
return "我是:"+this.name+",我的成绩是:"+this.score;
}
}
3、Java判断对象是否为同一引用(如使用equals()方法),自定义类需要重写hashCode()和equals()方法。
class Person implements Comparable<Person>{
private String name="";
private double score=0.0;
public Person(String name,double score){
this.name=name;
this.score=score;
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return (int)(this.name.hashCode()*this.score);
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
Person cc=(Person)obj;
return this.name==cc.name&&this.score==cc.score;
}
}