调用Set中克隆接口出错小程序,各位帮忙解释下.
有个小小的疑问请教一下:下面这个简单的小程序中,为什么不能写成注释那样呢?HashSet实现了Set接口,所以HashSet的实例该是Set的实例,为什么如果写成Set hs=new HashSet(),那么
程序当中Set hs2=(Set)hs.clone();这一行就会报错,说没有clone()这个方法啊?哪位知道的朋友解释下.
import java.util.*;
class HashTest
{
public static void main(String[] args)
{
Student st1 = new Student(1,"zhangsan");
Student st2 = new Student(3,"lisi");
Student st3 = new Student(2,"wangwu");
HashSet hs = new HashSet();//为什么这一行不能换成 Set hs = new HashSet();
hs.add(st1);
hs.add(st2);
hs.add(st3);
Set hs2 = (Set)hs.clone();
Iterator it = hs2.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
}
class Student implements Cloneable
{
int num;
String name;
Student(int num , String name)
{
this.num=num;
this.name=name;
}
public Object clone()
{
try
{
return super.clone();
}
catch(CloneNotSupportedException e)
{
return null;
}
}
public String toString()
{
return "num : "+num+","+"name : "+name;
}
}