简体   繁体   English

如何访问对象数组的数组元素?

[英]How to access elements of an array of an array of objects?

public class arrayOfArrays{ 
       public Object[] array1;
       public int size;           

       arrayOfArrays(){
            array1 = new Object[10];
            array1[0] = new arrayOfInts();
   }
}

class arrayOfInts{
      public Integer[] array2;
      public int size;

      arrayOfInts(){
         array2 = new Integer[10]; 
    }
}

I am trying to create a 2d array of some sort that has varying length of the arrays that are contained within it.我正在尝试创建某种二维数组,其中包含的数组长度各不相同。 For example, array1[0] will have an array of Ints that has a length of 3. array1[1] will have an array of Ints of length 5. and so on.例如,array1[0] 将有一个长度为 3 的 Int 数组。array1[1] 将有一个长度为 5 的 Int 数组,依此类推。

If I want to access elements of array2 from within my arrayOfArrays class.如果我想从我的 arrayOfArrays 类中访问 array2 的元素。 How would I accomplish that?我将如何做到这一点?

I have tried: array1[this.size].array2[size] = x;我试过: array1[this.size].array2[size] = x; However, this gives me an error.但是,这给了我一个错误。 Do I need to cast the second array?我需要投射第二个数组吗? Any help would be appreciated.任何帮助,将不胜感激。 Cheers干杯

I don't really understand why you creates those classes.我真的不明白你为什么创建这些类。

You can simply store any kind of things in an Object array.您可以简单地将任何类型的东西存储在 Object 数组中。

Object[] array1 = new Object[ 5 ];
Random rd = new Random();

for( int i = 0; i<5; i++ )
  array1[ i ] = new int[ rd.nextInt( 5 ) + 1 ];

System.out.println( Arrays.deepToString( array1 ) );

Here i've created 5 int array with random size.在这里,我创建了 5 个随机大小的 int 数组。

The problem is that you have to cast the result of array1[i] into an int[] as far as you define it as an Object[]问题是您必须将 array1[i] 的结果转换为 int[],只要您将其定义为 Object[]

int[] o1 = ( int[] ) array1[ 1 ];
System.out.println( o1 );

A simpler solution would probably be to use a list on Integer arrays.一个更简单的解决方案可能是在整数数组上使用列表。 This way there is non needs to cast.这样就不需要投射了。

List<Integer[]> list1 = new ArrayList<>();

for( int i = 0; i<5; i++ )
  list1.add( new Integer[ rd.nextInt( 5 ) + 1 ] );

for( Integer[] array : list1 )
  for( int i=0;i<array.length;i++)
    array[i] = rd.nextInt( 100 );

System.out.println(  Arrays.deepToString( list1.toArray() ) );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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