创建一个只能存放String的泛型ArrayList的语句
时间: 2024-02-18 13:59:36 浏览: 67
可以使用以下语句来创建一个只能存放String的泛型ArrayList:
```java
ArrayList<String> list = new ArrayList<String>();
```
这个ArrayList只能存储String类型的元素,如果尝试将其他类型的元素添加到这个列表中,将会编译时出错。
相关问题
List<String>arrayList = new ArrayList< String>();
List<String>arrayList = new ArrayList< String>();是一个创建ArrayList对象的语句,其中List<String>表示这是一个泛型类型,只能存储字符串类型的数据。ArrayList是List接口的一个实现类,可以用来创建一个可变长度的数组。下面是一个例子:
```java
List<String> arrayList = new ArrayList<String>();
arrayList.add("apple");
arrayList.add("banana");
arrayList.add("orange");
System.out.println(arrayList); // 输出:[apple, banana, orange]
```
ArrayList<Object> lists = new ArrayList<String>(); ArrayList<String> lists = new ArrayList<Object>(); 如何使用泛型通配符?将错误的语句修改正确
使用泛型通配符来解决这个问题可以这样写:
ArrayList<?> lists = new ArrayList<String>();
ArrayList<String> lists = new ArrayList<String>();
或者这样写:
ArrayList<? extends Object> lists = new ArrayList<String>();
ArrayList<String> lists = new ArrayList<String>();
请注意,这两种写法编译器可以通过,但是第一种写法中的 `lists` 对象不能添加任何元素。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)