java学习之 容器Collection接口---hashCode

17 篇文章 0 订阅

java基础中的容器:

 

 

Collection接口

 

 

      hashCode

 

实例(马士兵视频源码):

import java.util.*;
public class basicCollectionTest2 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Collection c=new HashSet();
		
		c.add("11");
		c.add(new Name("f1","wang"));
		c.add("zhu");
		System.out.println(c);
		
		//remove   删除
		c.remove("11");
		c.remove(new Name("f1","wang"));
		c.remove("zhu");
		System.out.println(c);
	}

}


class Name {
	
	String firstname,lastname;
	
	//构造函数
	public Name(String firstname,String lastname){
		
		this.firstname=firstname;
		this.lastname=lastname;
		
	}	
	
	//返回
	public String getFirstname(){
		return firstname;
	}
	
	public String getLasttname(){
		return lastname;
	}
	
	public String toString(){
		return lastname+" "+firstname;
	}

	/*
	 * 重写equals方法后要同时重写hashCode方法
	 * 当对象变为索引时,需要hashCode方法
	 * (non-Javadoc)
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
    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 hashCode(){
    	return firstname.hashCode();
    }
	
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值