【问题标题】:Accessing Objects from a 2d Arraylist of Custom Objects in Java从 Java 中的自定义对象的二维数组列表访问对象
【发布时间】:2017-09-06 16:51:47
【问题描述】:

考虑以下情况。我有 2 个类,如下所示:

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*/

  }

现在还有一个类,我在其中创建了CustomObject的ArrayList[][],方法如下

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

 }

我找不到完成此类作业的方法。如果您需要更多信息,请发表评论!

【问题讨论】:

  • new ArrayList[100][100] ???
  • @ANS 这是一个ArrayList 的多维数组。它编译。
  • @VinceEmigh 它编译不好。它编译时带有警告。
  • @TomHawtin-tackline 我没有说很好,我只是说它可以编译,就像“语法允许它”一样。跨度>

标签: java generics arraylist multidimensional-array


【解决方案1】:

arrCO[indx][indy] 引用的对象是一个 ArrayList

arrCO 是自定义对象列表的二维数组

执行此操作以访问您要访问的内容:

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

现在您可以访问 arrInt 和 objectSOC 了

customObj.arrInt & customObj.objectSOC

【讨论】:

  • 非常感谢!我以错误的方式解释了声明本身。只是补充一点,如果有人想在脑海中进一步可视化它,在任何 IDE 中以调试器模式查看变量,NetBeans/Eclipse 可能会有所帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多