0

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.

7
  • try ArrayList class, present in java.utils package Commented Dec 5, 2014 at 17:12
  • @Sarthak Mittal - ArrayList does not autofill. You cannot set an element past the end. Commented Dec 5, 2014 at 17:13
  • @jalynn2 yeah you are right, but what do you mean by, "You cannot set an element past the end"? Commented Dec 5, 2014 at 17:15
  • @SarthakMittal If there are x elements in the list, then you can't add another element on position y if y > x. In other words: if there are 5 elements in a list, list.add(10, "blub"); will fail. Commented Dec 5, 2014 at 17:17
  • If the ArrayList is empty, you may only set into element 0. If it has one item, you may only set into element 0 and 1, etc. If you try to set into a greater index, you will get IndexOutOfBoundsException. Commented Dec 5, 2014 at 17:18

3 Answers 3

2

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); 
}
Sign up to request clarification or add additional context in comments.

Comments

1

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]

Comments

0

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

1 Comment

Arrays.fill functions on ordinary, static arrays, and throws an exception if the index is out of bounds. It expands nothing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.