简体   繁体   中英

JavaScript style array filling in Java

In JavaScript, the following:

var a = [];
a[20] = "hello";
console.log(JSON.stringify(a));

would yield:

[null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,"hello"]

Is there a list type in Java that will auto expand when setting values beyond it's current bounds? A map isn't practical because I also need to know the array dimension.

In the standard JDK there is not such a class.

Your best bet is probably to create a wrapper around an ArrayList and provide methods like set(int index,Object value)

Its implementation would look like this:

public void set(int index,Object value) {
   while (list.size() <= index) {
       list.add(null); // filling the gaps
   }   
   list.set(index,value); 
}

Such implementation is not provided in the standard JDK, but you can use a GrowthList (from Apache Commons Collections ).

List<String> list = new GrowthList<>(); //[]
list.add(5, "test"); //[null, null, null, null, null, test]

您可以使用Arrays.fill查看此响应

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