这几天在总结集合这部分,做了几个练习,这几个练习里面都使用到了contains和instanceof;原本觉得风马牛不相及的东西,突然间让我混乱了,自己敲代码的时候,好几次错用了contains和instanceof, 
先把代码贴上,然后向大家说说我的疑惑 
- import java.util.*;
 
  
- class Person
 
 - {
 
 -         private String name;
 
 -         private int age;
 
 -         Person(String name,int age)
 
 -         {
 
 -                 this.name = name;
 
 -                 this.age = age;
 
 -         }
 
 -         public boolean equals(Object obj)
 
 -         {
 
 -                 /*
 
 -                 这里的instanceof
 
 -                 */
 
 -                 if(!(obj instanceof Person))
 
 -                         return false;
 
  
-                 Person p = (Person)obj;
 
  
-                 return this.name.equals(p.name) && this.age == p.age;
 
 -         }
 
 -         public String getName()
 
 -         {
 
 -                 return name;
 
 -         }
 
 -         public int getAge()
 
 -         {
 
 -                 return age;
 
 -         }
 
 - }
 
 - class ArrayListTest2 
 
 - {
 
 -         public static void sop(Object obj)
 
 -         {
 
 -                 System.out.println(obj);
 
 -         }
 
 -         public static void main(String[] args) 
 
 -         {
 
 -                 ArrayList al = new ArrayList();
 
  
-                 al.add(new Demo());
 
  
-                 al.add(new Person("lisi01",30));
 
 -                 al.add(new Person("lisi02",32));
 
 -                 al.add(new Person("lisi02",32));
 
 -                 al.add(new Person("lisi04",35));
 
 -                 al.add(new Person("lisi03",33));
 
 -                 al.add(new Person("lisi04",35));
 
  
-                 
 
 -                 al = singleElement(al);
 
  
 
-                 Iterator it = al.iterator();
 
  
 
-                 while(it.hasNext())
 
 -                 {
 
 -                         Person p = (Person)it.next();
 
 -                         sop(p.getName()+"::"+p.getAge());
 
 -                 }
 
 -         }
 
  
 
-         public static ArrayList singleElement(ArrayList al)
 
 -         {
 
 -                 ArrayList newAl = new ArrayList();
 
  
-                 Iterator it = al.iterator();
 
  
-                 while(it.hasNext())
 
 -                 {
 
 -                         Object obj = it.next();
 
 -                         /*
 
 -                         这里的contains方法
 
 -                         */
 
 -                         if(!newAl.contains(obj))
 
 -                                 newAl.add(obj);
 
  
-                 }
 
  
-                 return newAl;
 
 -         }
 
 - }
 
  复制代码 让我混乱的地方: 
通过上面的代码大家会发现这两个词(暂时用词代替吧),有着类似的表面意思:包含 
我错用的状况是这样的,该用instanceof的地方使用了contains,也反过来用过。 
 
后来我查了下资料,了解了一点信息: 
instanceof : 关键字,常用于判断实例 
上面代码中的体现:两端都是对象 
contains() : String类中的方法 
 
 
 
上面代码中的体现:引用类型变量调用contains方法,传入的是对象。 
 
不过老感觉别扭啊,不知道是不是我有些知识点还没掌握, 
大家说下自己的意见。 
 
 
 |