开发者

Adding ArrayList elements efficiently

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


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.


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.


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


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜