容器回顾随笔

一、容器类List和Map实现Collection接口。但是,和Collection接口类似的,还有Collections类,Collections类提供方法实现容器类的排序、打乱顺序、复制、取最大值、取最小值、反转等功能。

二、规范化自定义类
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;
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值