zhuiyisinian
北顾.岛城
2016-10-01 14:57
采纳率: 81.8%
浏览 973
已采纳

java中链表的克隆问题

代码如下:

 import java.util.*;
public class Example12_6 {
   public  static void main(String args[]) {
      LinkedList<String> list1=new LinkedList<String>();
      list1.add("A");
      list1.add("B");
      list1.add("C");
      list1.add("D");
      list1.add("E");
      LinkedList<String> list2 =(LinkedList<String>)list1.clone();  //这里我有两个问题不明白,
            //第一是带有泛型信息的链表能这样强制转化吗?怎么感觉这样转化会出问题
            //第二是LinkedList中的clone方法不是浅复制吗?
            //那么list2中的元素指向的不也是list1中的元素吗?
            //那么下面对list1进行洗牌后list2中的元素怎么不变呢?
      System.out.print("链表中的数据:");
      Iterator<String> iter=list1.iterator();
      while(iter.hasNext()) {
         String str=iter.next();
         System.out.print(str+" ");
      }
      Collections.shuffle(list1);   //洗牌
      System.out.printf("\n洗牌后链表中的数据:");
      iter=list1.iterator();
      while(iter.hasNext()) {
         String str=iter.next();
         System.out.print(str+" ");
      }
      System.out.printf("\n链表中的数据:");
      iter=list2.iterator();
      while(iter.hasNext()) {
         String str=iter.next();
         System.out.print(str+" ");
      }
      Collections.rotate(list2,2);   //向右旋转2步
      System.out.printf("\n向右旋转2步后链表中的数据:");
      iter=list2.iterator();
      while(iter.hasNext()) {
         String str=iter.next();
         System.out.print(str+" ");
      }
   } 
}

本人还是小白一枚,虚心求教。

补充一下,关于上面我两个问题中,我第一个问题的疑惑来自于sun公司java泛型教程中的这段话:
Another implication of the fact that a generic class is shared among all its instances, is that it usually makes no sense to ask an instance if it is an instance of a particular invocation of a generic type:

 Collection cs = new ArrayList<String>();
if (cs instanceof Collection<String>) { ...} // illegal 

similarly, a cast such as

 Collection<String> cstr = (Collection<String>) cs; // unchecked warning

gives an unchecked warning, since this isn’t something the run time system is going to check for you. The same is true of type variables

 <T> T badCast(T t, Object o) {return (T) o; // unchecked warning }

Type variables don’t exist at run time. This means that they entail no performance overhead in either time nor space, which is nice. Unfortunately, it also means that you can’t reliably use them in casts.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • caozhy
    已采纳
    
                //第一是带有泛型信息的链表能这样强制转化吗?怎么感觉这样转化会出问题
                            没有问题,因为你的接收类型和clone的返回类型一样
                //第二是LinkedList中的clone方法不是浅复制吗?
                            是浅复制。clone和直接=的区别是,前者你从原来的列表删除、添加元素,不会影响第二个,=会影响。但是你修改元素对象本身,两者都会影响
                            正确的做法是循环,新建复制。
    
    点赞 评论

相关推荐