Java List Object instead of an Array

2019-09-02 04:29发布

I hava a Java map like this:

Map<String, Object> data = new HashMap<String, Object>();

And I am performing following operation on it:

data.put("case_ids", new int[] { 31527 });

Where case_ids is one of the attribute of 3rd party API. However, that API throws incorrect API request error and suggests me to use List object instead of an Array for:

data.put("case_ids", new int[] { 31527 });

Not an expert of List, any suggestions? Like data.put("case_ids", new List[] { 31527 }); ?

EDITED: Extending my current question (to avoid repost or similar question). What if I have huge set of values for above put operation and want to create a list of known values. I do not feel that it is a correct way to mention the list of values separated by commas like 31527, 31528, 31529, 31530, 31531,..etc. I would rather store this somewhere and just call that as a input here - data.put("case_ids", new int[] { input });. Also, is that possible to do without a file? Just want to avoid dependency on file.

4条回答
放我归山
2楼-- · 2019-09-02 04:45
List<Integer> mList = new ArrayList<Integer>;
mList.add(31527);
data.put("case_ids", mList);
查看更多
贼婆χ
3楼-- · 2019-09-02 04:56

List is an interface. Use a concrete class like data.put("case_ids", new ArraList<Integer>{ 31527 });

查看更多
冷血范
4楼-- · 2019-09-02 04:59

Probably the simplest way how to create a list from known values is

Arrays.asList(31527)

That would make your call

data.put("case_ids", Arrays.asList(31527));

supposing the API accepts a List as the value. Without the API documentation or the error message, we cannot tell what it really accepts.

There are other ways how to create List, such as new ArrayList<>(), etc., just check out the javadoc and concrete classes which implement the List interface.


Update: If you don't want an external file, I suppose you're fine with having the numbers in the source code. The simplest option is to have them somewhere as a static field

public static final int[] VALUES = {1, 2, 3, /*...*/};

which you can turn into a List (in Java 8) with Arrays.stream(VALUES).boxed().collect(Collectors.toList()) (see here).

I recommend using Guava library instead where you can create a safer immutable list directly with

public static final List<Integer> VALUES = ImmutableList.of(1, 2, 3) 

If you don't like having all values in the code like this, then you can read them from a resource file, but that would be for another question.

查看更多
Root(大扎)
5楼-- · 2019-09-02 05:02

You could use the following format

data.put("case_ids", Arrays.asList(new Integer[] { 31527 }));

If you have an array of integers the one you have mentioned the comments then you can use

int [] cases = { 10,20,30};
data.put("case_ids", Arrays.asList(cases));
查看更多
登录 后发表回答