views:

155

answers:

4

How would I shorten this?

int[] a1 = {2, 0, 1, 4, 3};
int[] a2 = {3, 1, 2, 0, 4};
int[] a3 = {4, 2, 3, 1, 0}; 
int[] a4 = {0, 3, 4, 2, 1};
int[] a5 = {1, 4, 0, 3, 2};
ArrayList<int[]> array = new ArrayList<int[]>();
array.add(a1);
array.add(a2);
array.add(a3);
array.add(a4);
array.add(a5);
+3  A: 
List<int[]> ints = Arrays.asList(new int[][]{{2, 0, 1, 4, 3},
                                             {3, 1, 2, 0, 4},
                                             {4, 2, 3, 1, 0},
                                             {0, 3, 4, 2, 1},
                                             {1, 4, 0, 3, 2}});

is one way.

Edit: bmargulies rightly pointed out that the resulting List is not necessarily an ArrayList; if one is needed, you can then copy the elements into a new one.

danben
upvoted, but is the result actually an ArrayList?
bmargulies
This is Java 1.4, yes? In Java 5+ you'd just list the elements: Arrays.asList({1,2,3},{4,5,6}); The resulting list is fixed-length.
Michael Brewer-Davis
@bmargulies: not necessarily, but the conversion is simple enough. I'll add that to the answer.
danben
@Michael Brewer-Davis: I'd think that would work, but for some reason it gives a compile-time error.
danben
Seems like it's because there's nothing to cause creation of an array object.
danben
`Arrays.asList` does return an `ArrayList`, but it is a `java.util.Arrays.ArrayList` not a `java.util.ArrayList` (nice naming). :)
Tom Hawtin - tackline
Seems that YuppieNetworking has shown the best syntax for asList() (better than Arrays.asList(new int[]{1,2,3}, new int[]{4,5,6});) All in all, I'd stick with the original or Kevin Connor's and not worry about asList().
Michael Brewer-Davis
A: 

With Arrays.asList

    int[][] a = {
            {2, 0, 1, 4, 3},
            {3, 1, 2, 0, 4},
            {4, 2, 3, 1, 0}, 
            {0, 3, 4, 2, 1},
            {1, 4, 0, 3, 2}
    };
    List<int[]> arr = Arrays.asList(a);
YuppieNetworking
A: 

Do you just want 'array' to contain the same information? Something like:

int[][] a = {{2, 0, 1, 4, 3}, {3, 1, 2, 0, 4}, {3, 1, 2, 0, 4}, {0, 3, 4, 2, 1}, {1, 4, 0, 3, 2}};
    ArrayList<int[]> array = new ArrayList<int[]>();
    for(int[] i: a)
        array.add(i);

is shorter than what you posted. Are you trying to shorten the declaration of the variables a1-5, or the repetitive calls to add, or both?

Paul Rayner
+2  A: 

K.I.S.S.:

ArrayList<int[]> array = new ArrayList<int[]>();
array.add(new int[] { 2, 0, 1, 4, 3 });
array.add(new int[] { 3, 1, 2, 0, 4 });
array.add(new int[] { 4, 2, 3, 1, 0 });
array.add(new int[] { 0, 3, 4, 2, 1 });
array.add(new int[] { 1, 4, 0, 3, 2 });

It does the same thing as the old code, is shorter, and performs fine.

Kevin Conner