我是否误解了阵列列表的某些内容?

时间:2014-04-14 04:47:30

标签: java

编写一个名为toArrayList()的新方法,该方法返回包含所有元素的ArrayList<E> object 调用列表,顺序相同(即,头节点的数据应该存储在返回的数组列表的索引0中)。

这就是我们提出的一个问题。我写了一个循环,它应该把调用列表中的元素放在一个新的数组中,但是当我想返回ArrayList<E>时,我得到一个错误说,&#34;找不到符号 - 类{ {1}}&#34。

我可以写一个ArrayList课程,但我们的老师总是一步一步地完成课程。如果有某种类或方法,我们必须写作完成作业,他告诉我们。所以我觉得我在这里遗漏了一些东西,因为在作业中没有任何地方告诉我们写一个ArrayList

3 个答案:

答案 0 :(得分:1)

您正在寻找班级java.util.ArrayList。看看文档。您可以直接将elements添加到其中,而无需使用primitive数组。

答案 1 :(得分:1)

您是否在文件顶部有一个import语句。?

import java.util.ArrayList;

使用addAll(Collection c)方法将所有元素从给定List拉到新的ArrayList

答案 2 :(得分:0)

我倾向于在代码中更好地解释事情。

我们只是拿一个给定的列表并在这些示例中复制它。重要的方法是课堂底部的复制功能。

import java.util.List;
import java.util.ArrayList;

public class ListUtil{

    public static void main(String[] args){
        List<Integer> ints = new ArrayList<Integer>();
        ints.add(1);
        ints.add(2);
        ints.add(3);

        List<Integer> copyOfInts = copy(Integer.class, ints);
        System.out.println("The value of the first element in both lists is 1: " + copyOfInts.get(0) == ints.get(1));
        System.out.println("The two lists are not the same: " + ints == copyOfInts);
        ints.remove(0);
        System.out.println("The first ints has 2 elements : " + ints.size() == 2);
        System.out.println("The first copys have 3: " + coyOfInts.size() == 3);

        String[] strings = {"String 1", "String 2", "String 3"};
        List<String> copyOfStrings = copy(String.class, strings);
        System.out.println("The second element of the copy is \"String 2\": " + "String 2".equals(strings.get(0));
    }

    /**
     * I create copies of arrays of type
     * @Param Class<T> typeOfT - the type that the list of T represents. This is useful to tell teh compiler what type the list really is at runtime.
     * @Param T[] the array you want to copy
     * @Return List<T> the copied list
     */

    public static final <T> List<T> copy(Class<T> typeOfT, T[] arrayToCopy){
        List<T> newList = new ArrayList<T>();

        for(int i = 0; i < arrayToCopy.length(); i++){
            newList.add(arrayToCopy[i]);
        }

        return newList;

    }

    /**
     * I create copies of lists of type
     * I am also what is called a paramaterized method. I am type safe, but can work on many different types.
     * @Param Class<T> typeOfT - the type that the list of T represents. This is useful to tell teh compiler what type the list really is at runtime.
     * @Param List<T> the list you want to copy
     * @Return List<T> the copied list
     */

      public static final <T> List<T> copy(Class<T> typeOfT, List<T> listToCopy){
        List<T> newList = new ArrayList<T>();
        newList.addAll(listToCopy);
        return newList;
    }   
}

http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html