- package SetPackage;
- import java.util.HashSet;
- import java.util.Iterator;
- public class HashSetDemo1 {
- public static void main(String[] args)
- {
- HashSet hs = new HashSet();
- hs.add("Java04");
- hs.add("Java03");
- hs.add("Java02");
- hs.add("Java02");
- hs.add("Java01");
- hs.add("Java01");
- hs.add("Java01");
- for(Iterator it = hs.iterator(); it.hasNext();)
- {
- Person2 obj = (Person2) it.next();
- System.out.println(obj.toString()+" ");//迭代器输出
- }
- }
- }
- class Person2
- {
- private String name;
- private int age;
- Person2(String name,int age)
- {
- this.name = name;
- this.age = age;
- }
- public void setName(String name)
- {
- this.name = name;
- }
- public void setAge(int age)
- {
- this.age = age;
- }
- public String toString()
- {
- return this.name+this.age;
- }
- public int hashCode()
- {
- return name.hashCode()+age*13;
- }
- public boolean equals(Object obj)
- {
- Person2 p =(Person2)obj;
- if(obj instanceof Person2)
- return false;
- return this.name.equals(p.name) && this.age == p.age;
- }
- }
复制代码 抛出这个异常java.lang.ClassCastException:当试图将对象强制转换为不是实例的子类时,抛出该异常
可是我另外写的一个demo跟这个几乎一样的 可是那个为什么就可以强转呢?
|
|