-
package
v2; -
import
java.util.*; -
public
class BasicContainer { -
public static void main(String[] args ){ -
Collection c = new HashSet (); -
c .add( "hello" ) ; -
System. out .println( c ); -
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" , "l1" ))); //删除对象时调用equals方法对比两个对象是否一致 -
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 hashCode(){ -
return firstName .hashCode(); -
} -
}
-
-
Java 容器 collection hashCode
最新推荐文章于 2022-02-05 12:32:16 发布