AaronF
AaronF

Reputation: 3081

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.

Upvotes: 0

Views: 69

Answers (3)

Alexis C.
Alexis C.

Reputation: 93852

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]

Upvotes: 1

cesar_sr91
cesar_sr91

Reputation: 130

You can use Arrays.fill.Take a look at this response.

Upvotes: 0

Zo72
Zo72

Reputation: 15325

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

Upvotes: 2

Related Questions