Any way to insert an anonymous array into a collection?

I found a lot of entries here that say

someFunc(new int[]{1,2,3});

works to call methods and is used in a for / each loop.

// ======

How about an appointment in the collection?

I tried this:

ArrayList<int[]> data = new ArrayList<int[]>();
data.add(new int[]{21, 19629});

and I get an "id" and an "illegal type start".

Is there anything I can do to make this work?

+3
source share
5 answers

You have created a list of arrays. That was what you intended, or you wanted to ask about something like

ArrayList<Integer> data = new ArrayList<Integer>();
data.add(new int[]{1,2,3});

?

In any case, familiarize yourself with the classes Arraysand Collections- they contain many utilities that come in handy in such cases.

+1

:

List<String> myList = Arrays.asList("Hello", "There", "Foo", "Bar);

, , . , , UnsupportedOperationException. , , ,

+1

guava, google.

(...), , .

.

.

import static com.google.common.collect.ImmutableList.of;
...

someFunc(of("abc","def","ghi"));

someFunc .

0

, , .

public static void main(String[] args) {
    List<int[]> data = new ArrayList<int[]>();
    data.add(new int[]{21, 19629})
    for(int[] tab : data){//I loop each tab (only one here)
        for(int i: tab){//I loop each values
            System.out.println(i);
        }
    }

}

21 19629

0

, . .

data.add(new int [] {21, 19629});

" " " ".

", " data.add(...), , , , . , , , data.add() .

" " , , , .

, arg.

int[] nums = new int[] {0,1,2};   
data.add(nums);

ArrayList.add() - ArrayList. JavaGlossary .

0

Source: https://habr.com/ru/post/1763989/


All Articles