1

So I was trying to add 2 dimensional arrays to an array list like this:

public class game{

        static ArrayList<Object> edges = new ArrayList<Object>();

        static void setEdges(){
            for(int i=0;i<8;i++){
                for(int j=0;j<8;j++){
                    edges.add( {9*i+j,9*i+j+1} );
                    edges.add( {9*i+j , 9*i+j+9} );
                }
            }
        }
   }

But it doesn't work. What does seem to work is this:

public class game{

        static ArrayList<Object> edges = new ArrayList<Object>();

        static void setEdges(){
            for(int i=0;i<8;i++){
                for(int j=0;j<8;j++){
                    int[] edge = {9*i+j,9*i+j+1};
                    int [] edge2 = {9*i+j , 9*i+j+9};
                    edges.add( edge2 );
                    edges.add( edge );
                }
            }
        }
   }

I can't understand why the simplest method doesn't work but the other does.

2 Answers2

3

It's because what you had written is not valid Java syntax:

edges.add( {9*i+j,9*i+j+1} );
edges.add( {9*i+j , 9*i+j+9} );

You need to explicitly specify that you're adding an array:

edges.add(new int[] {9 * i + j, 9 * i + j + 1});
edges.add(new int[] {9 * i + j, 9 * i + j + 9});
Jacob G.
  • 28,856
  • 5
  • 62
  • 116
-1

I think that normal because you trying to add a Integer into a intense to the array of object (edges) with out cast. So if you want that work replace Object by Integer :)