Question

I gott two toString() and want to print them both, by calling only one of them. I must have objects of class1 as Array and class2 as ArrayList.

Main:

 public static void main(String[] args) {
    Main main = new Main();
    Class1 []class1 = new Class1[2];
    ArrayList<Class2> class2List = new ArrayList<Class2>();

    for(int i=0; i<class1.length; i++){
        class1[i] = getClass1Obj();
        class2List.add(getClass2Obj());   
    } 

    for(int i=0; i<class1.length; i++){
        printClass1(class1, i);            
    }                
}

public static void print(Class1[] cls1, int index){
        System.out.println(cls1[index].toString());
}

Class1:

private Class2 class2;    

@Override
public String toString() {
    return getMethod() + getMethod2() + class2.toString();                             
}

Class2:

@Override
public String toString() {
    return getMethod3() + getMethod4();
}

This doesn't work. May it be because of the way I create the different objects?

Was it helpful?

Solution

You should add a reference to class2 when you create class1 instances

for(int i=0; i<class1.length; i++){
    class1[i] = getClass1Obj();
    Class2 class2 = getClass2Obj();
    class1[i].setClass2(class2);
    class2List.add(class2);   
} 

Remember to create a setClass2 method

public setClass2(Class2 class2) { this.class2 = class2; }

In this way, class1 will have a reference to class2 and can use class2 toString

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top