2013-05-19 48 views
0

我试图创建一个按字母顺序排列的列表中的程序,使用Collections.sort方法和java.util.List中,错误的是:1个错误和警告15发现:Java中的alphabetizing-错误和警告?

Error: java.util.List is abstract; cannot be instantiated 
-------------- 
** Warnings ** 
-------------- 
Warning: unchecked call to add(E) as a member of the raw type java.util.List 
Warning: unchecked method invocation: method sort in class java.util.Collections is applied to given types 
    required: java.util.List<T> 
    found: java.util.List 

我的代码:

public static void preset(){ 
    List words= new List(); 
    words.add("apple"); 
    words.add("country"); 
    words.add("couch"); 
    words.add("shoe"); 
    words.add("school"); 
    words.add("computer"); 
    words.add("yesterday"); 
    words.add("wowza"); 
    words.add("happy"); 
    words.add("tomorrow"); 
    words.add("today"); 
    words.add("research"); 
    words.add("project"); 
    Collections.sort(words); 




    } //end of method preset 

回答

1

正如错误所述,List是抽象的,您需要一些具体的实现。在你发布的情况下,ArrayList会做。

另请注意,您正在使用List作为原始类型;不要这样做(除非您在Java 5之前使用的版本)。使用类型参数对其进行参数化(这里是String)。

但也:不改变words声明是ArrayListList足够好(一般),并离开它不变,您将获得变更后的执行情况的能力。

结论:

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

,或者使用Java 7:

List<String> words= new ArrayList<>(); 
+0

感谢的作品也,我怎么打印此新排序列表?我试图打印它通过调用主要的方法,但这是行不通的 – user2399999

+0

你可以发布它是如何不工作? System.out.println(文字)应该足够了。 –

0

无法实例java.util.List,但它的一些实现。像(例如)java.util.ArrayList。请注意,它们是通用的。

就解决以下几点:

List words= new List(); 

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