Devendra Vyas
Devendra Vyas

Reputation: 95

Accessing Objects from a 2d Arraylist of Custom Objects in Java

Consider the following case. I have 2 classes as shown below:

public class CustomObject{

  public int a;
  public String xyz;
  public ArrayList<Integer> arrInt;
  public SomeOtherClass objectSOC;

   public CustomObject(){
   //Constructor
        }
  /*Followed by other methods in the class*/

  }

Now there is another class in which I have created ArrayList[][] of CustomObject, the way shown below

public class CustomObjectUtil{

 ArrayList<CustomObject>[][] arrCO = new ArrayList[100][100];

 public CustomObjectUtil(){
 //Assume there is an object of CustomObject class, let's call it ObjectCO, and a method that adds values to the arrCO using arrCO[i][j].add(ObjectCO);

 //Now, here I want to access objects from my 2D ArrayList as
   String stringCO = arrCO[indx][indy].xyz;
   ArrayList<Integer> arrIntCO = arrCO[indx][indy].arrInt;
   SomeOtherClass objectSOC_CO = arrCO[indx][indy].objectSOC;
 // But the above method is not allowed;
      }

 }

I could not find a way to do this type of assignment. Please comment if you need more info!

Upvotes: 0

Views: 394

Answers (1)

RajatJ
RajatJ

Reputation: 163

Object referenced by arrCO[indx][indy] is an ArrayList

arrCO is a 2-D array of List of CustomObject

do this to access what you're trying to access:

List<CustomObject> customObjList = arrCO[indx][indy];
CustomObject customObj = customObjList.get(0)  // assuming there are elements in this list

Now you can access arrInt & objectSOC as

customObj.arrInt & customObj.objectSOC

Upvotes: 1

Related Questions