从 List 更改为 ArrayList 会消除错误“List is an abstract and cannot be instantiated?

Changing from List to ArrayList removes the error "List is an abstract and can not be instantiated?

好吧,我是 List 的新手,我一直使用 Arrays,现在我正在编写一个程序,在创建数组之前我无法判断数组的大小,所以我我正在使用 List。问题是我有一个方法 returns none 重复数字的列表。

这是我的方法:

public static List<Integer> arrayOfNoneRepeatingDigits(int limit) {

List<Integer> list = new ArrayList<Integer>();

for(int i = 0; i < limit; i++){
        boolean ignore = false;
        for(int j = i; j > 0; j/=10){
            if(ignore == true) break;
            for(int k = j/10; k > 0; k/=10){
                if(j%10 == k%10){
                    ignore = true;
                    break;                        
                    }                    
                }               
            }
        if(ignore == false)list.add(i);                
        }    
return list;    
} 

首先我的方法数据类型是数组,但在我将其更改为列表后,这行代码出现错误:

List<Integer> list = new List<Integer>();

网上查了一下,原来应该把List换成ArrayList。我做到了,现在错误消失了,但我不知道为什么。

这个:

List<Integer> list = new List<Integer>();

没有意义,因为您试图直接实例化一个 接口 ,这是不具体的,因此除非您创建一个匿名的,否则您无法执行此操作内部 class 与实例化,你真的 不想 想做的事情。最佳解决方案:坚持使用 ArrayList 进行具体实现(或根据您的要求使用 LinkedList)。例如,

List<Integer> list = new ArrayList<>();

出于好奇,是什么促使您在已有工作代码的情况下进行此更改?

接口无法实例化,所以没有 new List<Integer> 东西。接口的方法没有实现。这些方法的实现在子类中。 ArrayListList 的子类之一,因此您可以使用第一个代码片段。

写成new List<Integer>就没有意义了。因为 List 的方法没有实现,所以当你调用 add 方法时,编译器如何知道方法中的实现是什么?

列表是一个接口。这意味着List中没有属性,并且方法被声明但没有定义。因此,没有足够的信息来实例化它并发生错误。当您尝试实例化抽象对象时,也会发生这种情况 class.

可以声明interface/abstractclass的对象,但不能实例化。所以你有两个选择。

List<Integer> list = new ArrayList<Integer();
((ArrayList)list).method(); 
//cast it into ArrayList. 
//If you try to cast a wrong class, then the error will be printed out.

这种方式需要额外的转换。否则,您也可以使用 ArrayList 声明。

ArrayList<Integer>list = new ArrayList<Integer>();