Java 容器 collection hashCode

来源:互联网 发布:蜂蜜和四叶草 知乎 编辑:程序博客网 时间:2024/05/18 02:57
  1. package v2;
  2. import java.util.*;
  3. public class BasicContainer {
  4.  public static void main(String[] args){
  5.   Collection c new HashSet();
  6.   c.add("hello");
  7.   System.out.println(c);
  8.   c.add(new Name("f1","l1"));
  9.   c.add(new Integer(100));
  10.   c.remove("hello");
  11.   c.remove(new Integer(100));
  12.   System.out.println(c.remove(new Name("f1","l1")));//删除对象时调用equals方法对比两个对象是否一致
  13.   System.out.println(c);
  14.  }
  15.  
  16. }
  17. class Name{
  18.  private String firstName,lastName;
  19.  public Name(String firstName,String lastName){
  20.   this.firstName firstName;
  21.   this.lastName lastName;
  22.  }
  23.  
  24.  public String getFirstName(){
  25.   return firstName;
  26.  }
  27.  public String getLastName(){
  28.   return lastName;
  29.  }
  30.  public String toString(){
  31.   return firstName +" lastName;
  32.  }
  33.  
  34.  public boolean equals(Object obj){
  35.   if (obj instanceof Name){
  36.    Name name (Name) obj;
  37.    return firstName.equals(name.firstName&&
  38.      lastName.equals(name.lastName);
  39.   }
  40.   return super.equals(obj);
  41.  }
  42.  public int hashCode(){
  43.   return firstName.hashCode();
  44.  }
  45. }
  46.  
  47.  
0 0
原创粉丝点击