Reputation: 3081
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
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
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