【容器】Collection接口---hashCode

weitao00 2011-07-04

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();
    }
	
}
 

相关推荐