调用Set中克隆接口出错小程序,各位帮忙解释下.

那个天真的人 2009-01-22 07:42:58
有个小小的疑问请教一下:下面这个简单的小程序中,为什么不能写成注释那样呢?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;
}

}
...全文
62 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
那个天真的人 2009-01-22
  • 打赏
  • 举报
回复
原来这样,我原本以为在Set中找不到clone方法,由于多态会到子类中去找呢,呵呵,谢谢两位了.
chenchuanfeng001 2009-01-22
  • 打赏
  • 举报
回复
Set hs2=(Set)hs.clone();这一行就会报错.
因为clone()是HashSet中定义的方法,Set接口没有声明该方法。
GkfSyser 2009-01-22
  • 打赏
  • 举报
回复
Set hs = new HashSet()把HashSet上转成Set,他是一个Set对象,有些HashSet有但是Set没有的方法就不能调用了

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧