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

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条回答

  • threenewbee 2016-10-01 16:30
    关注
    
                //第一是带有泛型信息的链表能这样强制转化吗?怎么感觉这样转化会出问题
                            没有问题,因为你的接收类型和clone的返回类型一样
                //第二是LinkedList中的clone方法不是浅复制吗?
                            是浅复制。clone和直接=的区别是,前者你从原来的列表删除、添加元素,不会影响第二个,=会影响。但是你修改元素对象本身,两者都会影响
                            正确的做法是循环,新建复制。
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器