2015-05-08 55 views
0
ArrayList Clothes = new ArrayList(); 
ArrayList dictionary = new ArrayList(); dictionary.add(Clothes); 

我可以通过ArrayList中输入复杂

Clothes.add("hello, world"); 

添加到衣服,但为什么我不能添加衣服是这样的:

(dictionary.get(0)).add("hello, world"); 

+0

你需要仿制药。 – SLaks

+1

你需要演员。 –

+0

在创建/初始化之前,您无法获得第0个元素 –

回答

2

您正在使用原始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<>(); 

编译器会知道,在dictionaryget方法将返回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<>(); 
+0

啊好吧。感谢man-那工作:)我只需要:ArrayList > dictionary = new ArrayList <>(); –

0

因为ArrayListObject S和(dictionary.get(0))的容器是一个Object,和Object没有add()方法。

您有几个选项。你可以转换为ArrayList或只是List

((List)dictionary.get(0)).add("hello, world"); 

或者你可以使用泛型

ArrayList<ArrayList> dictionary = new ArrayList<>(); 
0

首先,不要使用原始类型ArrayList,经过Generics lesson。其次,请遵循Java命名约定,并将Clothes重命名为clothes

现在让我们来回答你的问题的实际,当你做

dictionary.get(0) 

什么是返回对象的类型?它的类型是Object,它没有add方法。

2

你可以但你需要指定列表元素的类型。见下面的例子:

List<String> clothes = new ArrayList<>(); 
List<List<String>> dictionary = new ArrayList<>(); 
dictionary.add(clothes); 
(dictionary.get(0)).add("hello, world"); 
0

您的问题是一个类型指定所以当你dictionary.get(0)其返回类型为ObjectObject没有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");