简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM