Collection(一)初步

今天学习Collection内容, 借助于一个Collection例子,再熟悉其方法的同时,复习一下面向对象知识。

 

import java.util.ArrayList;
import java.util.Collection;

public class TestCollection {
	public static void main(String[] args) {
		Collection c = new ArrayList();//多态,父类引用指向子类对象
		c.add("hello");
		c.add(new Integer(100));
		c.add(new Name("li", "wi"));
		System.out.println(c.size());
		System.out.println(c);
		c.remove("hello");//挨个比较是否equals
		c.remove(new Integer(100));//Integer重写了equals方法,两个对象“==”
		System.out.println(c.remove(new Name("li", "wi")));//判断两个对象相等,需要在类中重写equals方法
		System.out.println(c);//默认调用了c.toString方法;若c中含有name对象,需要在Name类中重写toString方法
	}
}

Name类:

public class Name {
	private String firstName;
	private String lastName;
	public Name(String firstName, String lastName){
		this.firstName = firstName;
		this.lastName = lastName;
	}
	//当使用contains,removes时,需要在本类中重写equals方法
	public boolean equals(Object o){
		if(o instanceof Name){
			Name name = (Name)o;
			return (firstName.equals(name.firstName))&&(lastName.equals(name.lastName));
		}
		return super.equals(o);
	}
	//重写equals应该重写hashCode方法,两对象相互equals他们的hashCode必须相等;
	//当一个对象作为索引(Map里的键)时要用hashCode
	public int hashCode(){
		return firstName.hashCode();
	}
	public String toString(){
		return firstName+","+lastName;
	}
}


需要注意的是:
1.在本例中使用多态,Collection c = new ArrayList(),c只能调用父类Collection中的方法,对ArrayList中特有的方法是无效的。所以当new出来的对象类型改变时,对于c的使用不用更改。即在本例中若改为Collection c = new HashSet(),下面的代码不用修改。

2.重写equals应该重写hashCode方法,比较对象equals时,需要挨个对象进行比较,速度较慢,但是两对象相互equals他们的hashCode相等,所以可以直接比较对象的hashCode是不是相等,hashCode返回值是int,比较起来效率较高。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值