Collection接口
来源:互联网 发布:linux配置邮件服务器 编辑:程序博客网 时间:2024/05/02 00:22
1.容器类对象在调用remove,contains等方法时需要比较对象是否相等,这会涉及到对象类型的equals方法和hashCode方法;对于自定义的类型,需要重写equals方法和hashCode方法以实现自定义的对象相等原则。
2.注意:相等的对象应该具有相等的hash codes。
增加Name类的equals和hashCode方法如下:
public boolean equals(Object obj){if(obj instanceof Name){Name name=(Name) obj;return (Firstname.equals(name.Firstname))&&(Lastname.equals(name.Lastname));}return super.equals(obj);}public int hashcCode(){return Firstname.hashCode();}
import java.util.*;public class Basiccontainer {public static void main(String[] args){Collection c=new HashSet(); c.add("hello"); c.add(new Name("f1","l1")); c.add(new Integer(100)); c.remove("hello"); c.remove(new Integer(100)); System.out.println(c.remove(new Name("f1","ll1"))); System.out.println(c);}}class Name{private String Firstname,Lastname;public Name(String Firstname,String Lastname){ this.Firstname=Firstname;this.Lastname=Lastname;}public String getFirstname(){return Firstname;}public String getLastname(){return Lastname;}public String tostring(){return Firstname+" "+Lastname;}public boolean equals(Object obj){if(obj instanceof Name){Name name=(Name) obj;return (Firstname.equals(name.Firstname))&&(Lastname.equals(name.Lastname));}return super.equals(obj);}public int hashcCode(){return Firstname.hashCode();}}
运行结果:
false[Name@5dcba031]
0 0
- Collection接口
- collection接口
- Collection接口
- Collection接口
- collection接口
- Collection接口
- Collection接口
- Collection接口
- Collection接口
- Collection接口
- collection接口
- Collection接口
- Collection接口
- Collection接口
- Collection接口
- collection接口
- Collection接口
- Collection接口
- 关于Rxjava的使用总结
- 大数据隐私保护技术综述-大数据-2016
- [samtools]view命令简介
- JQuery中$.ajax() 中typedata的坑
- interface接口的作用
- Collection接口
- Codevs 1200 同余方程 2012年NOIP全国联赛提高组
- 前端跨域知识总结
- RecyclerView嵌入CheckBox带来的显示问题的解决办法
- C#内存释放(垃圾回收)
- POJ-1942-Paths on a Grid
- IOS开发者必看的105个全球最佳博客
- 个人记录-LeetCode 29. Divide Two Integers
- 【codevs 1380】没有上司的舞会