无法实例化List <string>

时间:2017-09-17 22:15:38

标签: java

我试图实例化一个String类型的List,当我有这个时;

List<String> names = new ArrayList<String>();

我收到编译时错误,说这些类型不兼容,但据我所知,这是你应该如何实例化List。

这是全班。

package listDriver;
import list.*;

/**
 * Test the List ADT.
 * 
 * @author (sdb) 
 * @version (Jan 2012)
 */
public class HomeworkArrayListDriver
{
    public static void main()
    {   
        List <String> names = new ArrayList<String>();
        System.out.println ("Testing ArrayLists");
        //names = new ArrayList <String> ();
        names.add ("jim");
        names.add ("mary");
        names.add ("joe");
        names.add ("sue");
        System.out.println (names.get(2));  // Should be joe
        names.set (2, "Joe");            
        System.out.println (names.get(2));  // Should be Joe
        System.out.println (names.size());  // Should be 4
        names.remove (0);
        System.out.println (names.size());  // Should be 3
        names.add(0,"joe");
        System.out.println (names.size());  // Should be 4
        System.out.println (names.get(3));  // Should be sue
        if (names.isEmpty())
            System.err.println ("Incorrect, error in isEmpty");
        names.clear();
        if (!names.isEmpty())
            System.err.println ("Incorrect, error in isEmpty or clear");

    }

}

2 个答案:

答案 0 :(得分:1)

我怀疑你的进口是错误的。

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

public class Main {
    public static void main(String... args) {
        List<String> list = new ArrayList<>();
        list.add("3")
        System.out.println(list);
    }
}

答案 1 :(得分:-1)

ArrayList包中设置list课程,在List包中实施list课程。