ArrayList Clothes = new ArrayList();
ArrayList dictionary = new ArrayList(); dictionary.add(Clothes);
我可以通过ArrayList中输入复杂
Clothes.add("hello, world");
添加到衣服,但为什么我不能添加衣服是这样的:
(dictionary.get(0)).add("hello, world");
?
ArrayList Clothes = new ArrayList();
ArrayList dictionary = new ArrayList(); dictionary.add(Clothes);
我可以通过ArrayList中输入复杂
Clothes.add("hello, world");
添加到衣服,但为什么我不能添加衣服是这样的:
(dictionary.get(0)).add("hello, world");
?
您正在使用原始ArrayList
s。因此,get
方法返回Object
,并且Object
没有add
方法。
取而代之,请使用ArrayList
的通用形式,传递类型参数以指定每个ArrayList
可容纳哪些对象。
// holds Strings
ArrayList<String> clothes = new ArrayList<>();
// holds ArrayLists of Strings
ArrayList<ArrayList<String>> dictionary = new ArrayList<>();
编译器会知道,在dictionary
的get
方法将返回ArrayList<String>
,以便它可以验证您的来电add
。
dictionary.get(0).add("hello, world");
顺便说一句,这是一般的代码到接口的最好的事情,这是List
这里:因此
// holds Strings
List<String> clothes = new ArrayList<>();
// holds Lists of Strings
List<List<String>> dictionary = new ArrayList<>();
啊好吧。感谢man-那工作:)我只需要:ArrayList
因为ArrayList
是Object
S和(dictionary.get(0))
的容器是一个Object
,和Object
没有add()
方法。
您有几个选项。你可以转换为ArrayList
或只是List
:
((List)dictionary.get(0)).add("hello, world");
或者你可以使用泛型
ArrayList<ArrayList> dictionary = new ArrayList<>();
首先,不要使用原始类型ArrayList
,经过Generics lesson。其次,请遵循Java命名约定,并将Clothes
重命名为clothes
。
现在让我们来回答你的问题的实际,当你做
dictionary.get(0)
什么是返回对象的类型?它的类型是Object
,它没有add
方法。
你可以但你需要指定列表元素的类型。见下面的例子:
List<String> clothes = new ArrayList<>();
List<List<String>> dictionary = new ArrayList<>();
dictionary.add(clothes);
(dictionary.get(0)).add("hello, world");
您的问题是一个类型指定所以当你dictionary.get(0)
其返回类型为Object
和Object
没有add()
方法您dictionary
阵列没有。
只是声明你的阵列如下:
List<String> clothes = new ArrayList<String>();
ArrayList<List<String>> dictionary = new ArrayList<List<String>>();
,这应该工作:
clothes.add("hello, world");
(dictionary.get(0)).add("hello, world");
你需要仿制药。 – SLaks
你需要演员。 –
在创建/初始化之前,您无法获得第0个元素 –