代码如下:
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.