2017-01-08 112 views
-2

我有以下结构:的Java对象和ArrayList中

enter image description here

我有类AArrayList。这列出了来自类B的对象的元素。 B类的ArrayList中的对象是类型为C的对象。

欲添加一个方法A类,所以我可以(在ArrayList A特定索引的)一个元素添加到BArrayList类。

事情是这样的:

class A -> ArrayList A -> index 2-> B.add(some_element); 

这是直接可能的,或者我必须首先从A的数组列表中的对象,并进行修改和补充回来?

+0

这不是很清楚,你应该给三个类的代码。像A.get(2).geB()。add(“我是新的”); ? –

+0

你能分享一些代码来使一些事情更清楚吗? – Jonas

+0

你的建议是很好的解决方案。 'A'中的新方法将调用'B'中的方法将其添加到'B'的列表中。所以你需要在这两个类中编写新的方法。这很值得。 –

回答

0

如果你有三个类A,B和C,你可以简单地做这样的:

class A { 
    ArrayList<B> arrayListB = new ArrayList<>(); 
} 

class B { 
    ArrayList<C> arrayListC = new ArrayList<>(); 
} 

class C { 
    String cName; 
} 
//for example setting attribute cName, in first element of arrayListC, in the first element of array listB in obj a (of type class A) 
A a = new A(); 
a.arrayList.get(1).arrayList.get(1).cName="sth"; 

但我强烈鼓励你这样做,因为它违反了迪米特尔·link here法和here

+0

我同意这种沮丧。你为什么要展示糟糕的解决方案而不是好的解决方案? PS“得墨忒耳法”也被称为“不要与陌生人交谈”。 –