No primary or default constructor found for interface java.util.List"
时间: 2024-06-14 16:03:01 浏览: 22
在Java中,`java.util.List` 是一个接口,用于表示一个动态大小的有序元素集合,支持增删改查等操作。当你尝试创建 `List` 类型的一个实例,但没有找到合适的构造器(即没有默认的无参构造器,也没有任何参数的构造器),并且也没有显式指定任何实现类(如 `ArrayList`、`LinkedList` 等)时,编译器会抛出 "No primary or default constructor found for interface java.util.List" 的错误。
这个错误通常意味着你需要明确地创建一个 `List` 的实现类的实例,或者使用工厂方法来创建,例如:
```java
// 明确指定实现类
List<String> myList = new ArrayList<>();
// 使用工厂方法,如JDK提供的Arrays.asList
List<String> myList = Arrays.asList("a", "b", "c");
```
如果你尝试用 `new List()`,因为 `List` 是一个接口,没有实例化可能的操作,所以会导致这个错误。如果是为了避免硬编码实现,你可以考虑使用泛型和匿名内部类:
```java
List<String> myList = new ArrayList<String>() {
// 实现必要的 List 方法
};
```
相关问题
No primary or default constructor found for interface java.util.List
No primary or default constructor found for interface java.util.List 是一个常见的错误。这个错误意味着在创建List对象时没有找到主要的或默认的构造函数。List是一个接口,它不能直接实例化,所以你需要使用List的某个实现类来创建List对象,如ArrayList或LinkedList。这些实现类都有默认的构造函数,所以你可以使用它们来创建List对象。如果你需要使用其他实现类或自定义的类来创建List对象,你需要确保这个类有一个可用的构造函数。你可以通过提供实现类的全限定名来创建List对象,如new ArrayList<>()或new LinkedList<>()。
"No primary or default constructor found for interface java.util.List"
"No primary or default constructor found for interface java.util.List"这个错误通常出现在使用接口java.util.List时,没有找到主要或默认构造函数的情况下。接口是一种抽象的数据类型,它不能直接实例化,因此没有构造函数。构造函数是用于创建类的实例的特殊方法。
如果你遇到这个错误,可能是因为你在代码中尝试实例化一个接口,而不是具体的实现类。接口只定义了方法的签名,而不提供具体的实现。要解决这个问题,你需要使用一个实现了List接口的具体类来创建对象。
例如,你可以使用ArrayList类来实例化List接口的对象:
```
List<String> list = new ArrayList<>();
```
这样就可以创建一个ArrayList对象,并将其赋值给List接口的引用变量list。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)