Java ArrayList输入复杂性
我可以通过Java ArrayList输入复杂性,java,arraylist,Java,Arraylist,我可以通过 ArrayList Clothes = new ArrayList(); ArrayList dictionary = new ArrayList(); dictionary.add(Clothes); 但是为什么我不能像这样添加到衣服上: Clothes.add("hello, world"); ?您正在使用原始ArrayLists。因此,get方法返回一个Object,而Object没有add方法 相反,使用ArrayList的一般形式,传递类型参数以指定每个ArrayL
ArrayList Clothes = new ArrayList();
ArrayList dictionary = new ArrayList(); dictionary.add(Clothes);
但是为什么我不能像这样添加到衣服上:
Clothes.add("hello, world");
?您正在使用原始
ArrayList
s。因此,get
方法返回一个Object
,而Object
没有add
方法
相反,使用ArrayList
的一般形式,传递类型参数以指定每个ArrayList
可以包含哪些对象
(dictionary.get(0)).add("hello, world");
另一方面,通常最好对界面进行编码,即List
此处:
dictionary.get(0).add("hello, world");
//保存字符串
列表衣服=新的ArrayList();
//保存字符串列表
列表字典=新的ArrayList();
您正在使用原始ArrayList
s。因此,get
方法返回一个Object
,而Object
没有add
方法
相反,使用ArrayList
的一般形式,传递类型参数以指定每个ArrayList
可以包含哪些对象
(dictionary.get(0)).add("hello, world");
另一方面,通常最好对界面进行编码,即List
此处:
dictionary.get(0).add("hello, world");
//保存字符串
列表衣服=新的ArrayList();
//保存字符串列表
列表字典=新的ArrayList();
因为ArrayList
是对象的容器,而(dictionary.get(0))
因此是对象
,而对象
没有添加()
方法
你有两个选择。您可以强制转换到ArrayList
或仅List
:
// holds Strings
List<String> clothes = new ArrayList<>();
// holds Lists of Strings
List<List<String>> dictionary = new ArrayList<>();
或者可以使用泛型
((List)dictionary.get(0)).add("hello, world");
ArrayList dictionary=new ArrayList();
因为ArrayList
是对象的容器,而(dictionary.get(0))
因此是对象
,而对象
没有添加()
方法
你有两个选择。您可以强制转换到ArrayList
或仅List
:
// holds Strings
List<String> clothes = new ArrayList<>();
// holds Lists of Strings
List<List<String>> dictionary = new ArrayList<>();
或者可以使用泛型
((List)dictionary.get(0)).add("hello, world");
ArrayList dictionary=new ArrayList();
首先,不要使用原始类型ArrayList
,请查看。其次,请遵循Java命名约定,将衣服
重命名为衣服
现在让我们回答你的实际问题,当你这样做的时候
ArrayList<ArrayList> dictionary = new ArrayList<>();
返回对象的类型是什么?它的类型是对象
,没有添加
方法。首先,不要使用原始类型数组列表
,请检查。其次,请遵循Java命名约定,将衣服
重命名为衣服
现在让我们回答你的实际问题,当你这样做的时候
ArrayList<ArrayList> dictionary = new ArrayList<>();
返回对象的类型是什么?它的类型为对象
,没有添加
方法。您可以,但需要指定列表元素的类型。见下例:
dictionary.get(0)
List costs=new ArrayList();
列表字典=新的ArrayList();
添加(衣服);
(dictionary.get(0)).add(“你好,世界”);
可以,但需要指定列表元素的类型。见下例:
dictionary.get(0)
List costs=new ArrayList();
列表字典=新的ArrayList();
添加(衣服);
(dictionary.get(0)).add(“你好,世界”);
您的问题是您的字典
数组没有指定类型,因此当您执行字典时。get(0)
它的返回类型是对象
并且对象
没有添加()
方法
只需按如下方式声明数组:
List<String> clothes = new ArrayList<>();
List<List<String>> dictionary = new ArrayList<>();
dictionary.add(clothes);
(dictionary.get(0)).add("hello, world");
您的问题是您的字典
数组没有指定类型,因此当您执行字典时。get(0)
它的返回类型是对象
,而对象
没有添加()
方法
只需按如下方式声明数组:
List<String> clothes = new ArrayList<>();
List<List<String>> dictionary = new ArrayList<>();
dictionary.add(clothes);
(dictionary.get(0)).add("hello, world");
在创建/初始化第0个元素之前,无法获取该元素。。或者一个cast((ArrayList)(dictionary.get(0))…
@Lashane他添加了它,它只是隐藏在右边:)在创建/初始化它之前,你不能获取第0个元素。。或者一个演员((ArrayList)(dictionary.get(0))…
@Lashane他添加了它,它只是隐藏在右边:)啊,好的。谢谢你,伙计,这很有效:)我只需要:ArrayList dictionary=new ArrayList();啊,好的。谢谢你,伙计,这很有效:)我只需要:ArrayList dictionary=new ArrayList();