import java.util.*;class MyList {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<String>();
list.add("one ");
list.add("two ");
list.add("three ");
String[] sa = new String[3];
// insert code here
sa = (String []) list.toArray();
for (String s : sa)
System.out.print(s);
}
}

解决方案 »

  1.   

    toArray两种用法,最简单的解决办法是用有参数的:
    sa = list.toArray(new String[list.size()]); 用无参数的toArray没办法把Object[]强制转化成String[],改动比较大:
            Object[] sa = new String[3];
            // insert code here
            sa = (Object []) list.toArray();
            for (Object s : sa)
                System.out.print((String)s);
      

  2.   

    class MyList {
        public static void main(String[] args) {
            LinkedList<String> list = new LinkedList<String>();
            list.add("one ");
            list.add("two ");
            list.add("three ");
            String[] sa = new String[3];
            // insert code here
            list.toArray(sa);
          
            for (String s : sa)
                System.out.print(s);
        }
    }
    你可以看一下JDK的帮助文档中的List的toArray(T[] a)方法:
    <T> T[] toArray(T[] a)返回按适当顺序(从第一个元素到最后一个元素)包含列表中所有元素的数组;返回数组的运行时类型是指定数组的运行时类型。如果指定数组能容纳列表,则在其中返回该列表。否则,分配具有指定数组的运行时类型和此列表大小的新数组。 
      

  3.   


    你的我看懂了,谢谢,但是
    sa = (String []) list.toArray();
    这句话为什么不对还是不懂
    我感觉这蛮对的,list.toArray()返回object,强制转换成string,到底是哪里出问题呢,一直有ClassCastException?
      

  4.   

    之前有个帖子,就是说Object转换成String的问题··Object存放的是对象,而String存放的是字符·不能这样直接转换的·
      

  5.   

    看看这个:
    import java.util.LinkedList;class MyList {
        public static void main(String[] args) {
            LinkedList<String> list = new LinkedList<String>();
            list.add("one ");
            list.add("two ");
            list.add("three ");
            Object[] sa = new String[3];
            // insert code here
            sa = (Object[]) list.toArray();
            for (Object s : sa){
                if(s instanceof String){
                    System.out.print(s);
                }
            }
        }
    }