In Java 7, it is possible to write ArrayList<>, for example, with no type specified for the elements. Give an example of a situation in which this is allowed and explain why it is allowed?
时间: 2024-03-01 16:54:58 浏览: 82
JAVA ArrayList详细介绍(示例)
In Java 7 and later versions, it is possible to use the diamond operator `<>` to specify the type of a generic class with the type inference feature. For example, instead of writing `ArrayList<String>`, we can write `new ArrayList<>()` and the compiler will infer that it is an `ArrayList<String>` based on the context.
Here is an example of how the diamond operator can be used:
```
List<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
List<String> copy = new ArrayList<>(list); // diamond operator used for type inference
```
In this example, the `ArrayList` constructor is called with no type specified for the elements. However, the compiler is able to infer the type of the `ArrayList` based on the type of the `list` variable, which is a `List<String>`. Therefore, the `copy` variable is also inferred to be a `List<String>`.
The diamond operator is allowed in situations where the type of the generic class can be inferred from the context. This includes cases where the type is specified in the variable declaration or method signature, or where the generic class is being used in a method call with an argument of a specific type. By allowing the diamond operator, Java reduces the amount of boilerplate code needed to use generic classes and makes the code more concise and readable.
阅读全文