Cannot infer type arguments for TreeSet<>
时间: 2024-03-11 16:49:33 浏览: 141
This error occurs when the compiler cannot determine the type argument for a generic class, in this case, TreeSet. To fix this error, you need to provide the type argument when creating the TreeSet instance. For example, if you want to create a TreeSet of integers, you can do:
```
TreeSet<Integer> treeSet = new TreeSet<>();
```
Here, the type argument Integer is specified within the angle brackets <>. This tells the compiler that the TreeSet should only contain integers.
相关问题
List<ClientFollowUp> distinctList = Stream.concat(list.stream(), result.stream()) .distinct() .collect(Collectors.collectingAndThen( Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing( p -> Arrays.asList(p.getCustomerName())))), ArrayList::new)); 这代码中 报错Cannot infer type arguments for TreeSet<>
这个错误通常是由于 Java 泛型类型推断失败导致的。在这段代码中,由于 TreeSet 是一个泛型类,需要在创建对象时指定类型参数,但是没有指定类型参数,导致编译器无法推断类型参数,从而报错。
为了解决这个问题,你可以显式指定类型参数,例如:
```
List<ClientFollowUp> distinctList = Stream.concat(list.stream(), result.stream())
.distinct()
.collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<ClientFollowUp>(Comparator.comparing(
p -> Arrays.asList(p.getCustomerName())))),
ArrayList::new));
```
在创建 TreeSet 对象时,指定了类型参数为 ClientFollowUp,这样就可以避免该错误了。
Cannot infer type arguments for HashMap<>
`HashMap<>` is a generic class in Java, which means that it requires type arguments to be specified. You need to specify the type of keys and values. For example, if you want a `HashMap` that maps strings to integers, you would declare it as follows:
```java
HashMap<String, Integer> map = new HashMap<String, Integer>();
```
In this case, `String` is the type of keys, and `Integer` is the type of values. If you want to use type inference, you can omit the type arguments on the right-hand side of the assignment, and Java will infer them from the context:
```java
HashMap<String, Integer> map = new HashMap<>();
```
Here, Java infers the type arguments based on the left-hand side of the assignment.
阅读全文