简体   繁体   中英

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.

KISS :

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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