A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

import java.util.*;
public class CollcetionTest {
  public static void main(String[] args)
  {
   
   HashSet<People> hs = new HashSet<People>();
   hs.add(new People("zhangsan001",21));
   hs.add(new People("zhangsan02",20));
   hs.add(new People("zhangsan003",23));
   hs.add(new People("zhangsan",23));
   hs.add(new People("zhangsan",23));
   for (Iterator<People> it = hs.iterator();it.hasNext() ; )
   {
     People p =it.next();
    System.out.println(p.getName()+"..."+p.getAge());
   }
  
   HashSet<String> hs1 = new HashSet<String>();
   hs1.add("abc01");
   hs1.add("abc03");
   hs1.add("abc02");
   hs1.add("abc03");
   
   printCollection(hs1);
   
  }
  
  public static void printCollection(HashSet<?> hs1)
  {
   for (Iterator<?> it = hs1.iterator();it.hasNext() ; )
   {
   
    System.out.println(it.next());
   }
  }
}
class People<P extends People>                                                                                   
{
  private String name;
  private int age;
  People(String name,int age)
  {
   this.name = name;
   this.age = age;
  }
  public String getName()
  {
   return name;
  }
  public void setName(String name)
  {
   this.name = name;
  }
  public int getAge()
  {
   return age;
  }
  public void setAge(int age)
  {
   this.age = age;
  }
  //覆写hashCode方法比较
  public int hashCode()
  {
   return name.hashCode()+age*39;
  }
  public boolean equals(P p1)
  {
   //if(!(obj instanceof People))
    //return false;
   //People p = (People)obj;
   //System.out.println(this.name+".....equals"+p.name);
   return this.name.equals(p1.name)&&this.age==p1.age;
  }
}
泛型自定义对象的equlas怎么写?求高手!...怎么写都运行equals方法。。郁闷

3 个回复

倒序浏览
 ̄□ ̄||....equals不能写泛型.....后面有讲到了{:soso_e101:}
回复 使用道具 举报
你应该是想运行你的equals方法吧。把 public boolean equals(P p1)改为
public boolean equals(Object obj)  {
    if(!(obj instanceof People))
    return false;
   People p1 = (People)obj;
   System.out.println(this.name+".....equals"+p1.name);
   return this.name.equals(p1.name)&&this.age==p1.age;
  }
回复 使用道具 举报
袁培育 发表于 2012-4-23 17:11
你应该是想运行你的equals方法吧。把 public boolean equals(P p1)改为
public boolean equals(Object obj ...

哥们,你搞错意思了...不过现在已经知道了:victory:
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马