1.定义罪犯Criminal类,height(身高)/weight(体重)/blood(血型)/home(籍贯)属性。
重写hashcode和equals,使用四个属性的组合进行实现。
创建HashSet集合,里面存放20个Criminal对象,其中O型血2人,A型血3人,B型血4人,AB型血1人,其余血型不详。
注意:hashcode()方法实现时,要求身高、体重、和血型三个属性合成一个数字,实现两两比较的高效算法。
2.Map:
---------------------------------------------------------------------------------------
key(键) - value(值) :kv对.
创建HashMap,Person为key,Dog为value。
存放100元素,遍历map集合,两种方式。EntrySet + KeySet.
删除操作。remove();
----------------------------------------------------------------------------------------,
1,class Criminal{
int height;
int weight;
String blood;
String home;
Criminal(int height,int weight,String blood){
this.height=height;
this.weight=weight;
this.blood=blood;
}
@Override
public int hashCode() {
final int prime=31;
int result=1;
result=result*prime+(blood==null?0:blood.hashCode());
result=result*prime+height;
result=result*prime+weight;
return result;
}
@Override
public boolean equals(Object obj) {
if(this==obj){
return true;
}
if(obj==null){
return false;
}
if(obj.getClass()==Criminal.class){
Criminal temp=(Criminal)obj;
if(temp.height!=this.height){
return false;
}
if(temp.weight!=this.weight){
return false;
}
if(temp.blood==null&&this.blood==null){
return true;
}
if(this.blood.equals(temp.blood)){
return true;
}
}
return false;
}
}
public class container {
public static void main(String[] args) {
Set<Criminal> set=new HashSet<Criminal>();
set.add(new Criminal(188,56,"o"));
set.add(new Criminal(188,56,"o"));
set.add(new Criminal(188,56,"A"));
set.add(new Criminal(188,56,"A"));
set.add(new Criminal(188,56,"A"));
set.add(new Criminal(188,56,"B"));
set.add(new Criminal(188,56,"B"));
set.add(new Criminal(188,56,"B"));
set.add(new Criminal(188,56,"B"));
set.add(new Criminal(188,56,"AB"));
set.add(new Criminal(188,56,"unknwon"));
set.add(new Criminal(188,56,"unknwon"));
set.add(new Criminal(188,56,"unknwon"));
}
2,class Person{
String name;
Person(String name){
this.name=name;
}
}
class Dog{
String name;
Dog(String name){
this.name=name;
}
}
Map<Person,Dog> map=new HashMap<Person,Dog>();
for(int i=0;i<100;i++){
map.put(new Person("tom"+i), new Dog("BB"+i));
}
for(Entry<Person,Dog> entry:map.entrySet()){
System.out.println(entry.getKey()+""+entry.getValue());
}
for(Person p:map.keySet()){
System.out.println(map.get(p));
}