英文:
Autoboxing with primitive type in type of generic class?
问题
为什么 ```List<int> list1 = new ArrayList<>();``` 不起作用,而 ```List<int[]> list3 = new ArrayList<>();``` 和 ```List<Integer[]> list4 = new ArrayList<>();``` 起作用呢?
import java.util.ArrayList;
import java.util.List;
public class Test
{
public static void main(String[] args)
{
List
List
List<int[]> list3 = new ArrayList<>(); // 为什么起作用
List<Integer[]> list4 = new ArrayList<>(); // 为什么起作用
}
}
<details>
<summary>英文:</summary>
Why ```List<int> list1 = new ArrayList<>();``` doesn't working, and why ```List<int[]> list3 = new ArrayList<>();``` and ```List<Integer[]> list4 = new ArrayList<>();``` is working?
import java.util.ArrayList;
import java.util.List;
public class Test
{
public static void main(String[] args)
{
List<int> list1 = new ArrayList<>(); // why is doesn't working
List<Integer> list2 = new ArrayList<>();
List<int[]> list3 = new ArrayList<>(); // why working
List<Integer[]> list4 = new ArrayList<>(); // why working
}
}
</details>
# 答案1
**得分**: 2
在Java中,你有原始类型和引用类型。
`int`是一个原始类型,而`Integer`是一个引用类型。
在Java泛型中,你有*类型参数*。换句话说,类型参数是一个可以被引用类型名称替代的占位符。类型参数**不能**被原始类型替代。因此,`List<int>`是不允许的。
`List<Integer>`是允许的,因为`Integer`是引用类型。
在Java中,数组也是引用类型,即使它是由原始类型构成的数组。因此,`int[]`是一个引用类型,因此`List<int[]>`是允许的。
<details>
<summary>英文:</summary>
In java, you have primitive types and you have reference types.
`int` is a primitive type and `Integer` is a reference type.
In java generics you have *type parameters*. In other words, a type parameter is a place holder that can be replaced by the name of a reference type. A type parameter **cannot** be replaced with a primitive type. Hence `List<int>` is not allowed.
`List<Integer>` is allowed since `Integer` is a reference type.
In java, an array is also a reference type, even if it is an array of primitive types. Hence `int[]` is a reference type and therefore `List<int[]>` is allowed.
</details>
# 答案2
**得分**: 2
在Java泛型中,您永远不会将原始类型作为引用,例如:
```java
List<Integer> List<Double> ArrayList<Long>
因为它们不是对象!!在Java泛型中,我们使用对象编写通用类!!
英文:
In Java Generics, you never make a primitive type as a reference, like :
List<int> List<double> ArrayList<long>
because those aren't objects !!
int the java Generics, we code the generic classes with objects !!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论