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

© yang649981273 中级黑马   /  2014-7-18 19:51  /  1150 人查看  /  5 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. /*把相同元素删除运行之后不出结果是怎么回事啊?求指点!*/
  2. import java.util.*;
  3. class person
  4. {
  5.         private String name;
  6.         private int age;
  7.         person(String name,int age){
  8.                 this.name=name;
  9.                 this.age=age;
  10.         }
  11.         public boolean equals(Object obj){
  12.                 if(!(obj instanceof person))
  13.                         return false;
  14.                        
  15.                 person p=(person)obj;
  16.                 return this.name.equals(p.name)&&this.getAge()==p.getAge();
  17.         }
  18.         public String  getName(){
  19.                 return name;

  20.         }
  21.         public int getAge(){
  22.                 return age;
  23.         }
  24. }

  25. class  ArrayListTest
  26. {
  27.         public static void  sop(Object obj){
  28.                 System.out.println(obj);
  29.         }

  30.         public static void main(String[] args)
  31.         {
  32.                 ArrayList al=new ArrayList();
  33.                 al.add(new person("zhangsan1",31));
  34.                 al.add(new person("zhangsan2",32));
  35.                 al.add(new person("zhangsan3",33));
  36.                 al.add(new person("zhangsan4",34));
  37.                 al.add(new person("zhangsan3",33));
  38.                 al.add(new person("zhangsan4",34));
  39.                 al=singleElement(al);
  40.                 Iterator it=al.iterator();

  41.                 while(it.hasNext()){
  42.                         person p=(person)it.next();
  43.                         sop(p.getName()+"....."+p.getAge());
  44.                 }

  45.         }
  46.         public static ArrayList singleElement(ArrayList al){
  47.                 ArrayList newal=new ArrayList();
  48.                 Iterator it=al.iterator();
  49.                
  50.                 while(it.hasNext()){
  51.                         Object obj=it.next();
  52.                         if(newal.contains(obj))
  53.                                 newal.add(obj);
  54.                        
  55.                 }
  56.                 return newal;
  57.                
  58.         }
  59.        
  60. }
复制代码


5 个回复

倒序浏览
57行,逻辑错误:应该是obj不在newal中才往里添加。你写成了obj在newal中才添加。
回复 使用道具 举报
第57行目测改成  if(!(newal.contains(obj)))就对了
回复 使用道具 举报
fantacyleo 发表于 2014-7-18 20:02
57行,逻辑错误:应该是obj不在newal中才往里添加。你写成了obj在newal中才添加。 ...

O(∩_∩)O谢谢
回复 使用道具 举报
一十二。 来自手机 中级黑马 2014-7-19 18:20:04
报纸
已经解决了啊,白看半天了
回复 使用道具 举报
一十二。 来自手机 中级黑马 2014-7-19 18:21:22
地板
已经解决了啊,白看半天了
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马