-2

I have the following structure:

enter image description here

I have class A with an ArrayList. This lists elements that are objects from class B. Objects in Class B's ArrayList are if type class C.

I want to add a method to class A, so I could add an element (of specific index in ArrayList A) to class B's ArrayList.

Something like this :

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

Is this directly possible, or must I first get an object from A's array-list, and make changes and add it back?

rghome
  • 8,529
  • 8
  • 43
  • 62
  • It's not very clear, you should give code of the three classes. Something like A.get(2).geB().add("I'm new"); ? – Pascal Heraud Jan 08 '17 at 08:59
  • can you share some code to make some things more clear? – Jonas Jan 08 '17 at 09:17
  • What you suggest is the nice solution. The new method in `A` will call a method in `B` to add to `B`’s list. So you will need to write new methods in both classes. It’s worth it. – Ole V.V. Jan 08 '17 at 09:53

1 Answers1

0

If you have three classes A, B and C you could simply do it like this:

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";

BUT I strongly discourage you to do so, cause it violates the Law of Dimiter link here and here

Community
  • 1
  • 1
Mr.Q
  • 4,316
  • 3
  • 43
  • 40
  • I agree with the discouragement. Why are you showing the poor solution and not the good one? PS “Law of Demeter” is also known as “don’t talk to strangers”. – Ole V.V. Jan 08 '17 at 13:26