I think it\'s a fairly simple question, but I can\'t figure out how to do this properly.
I\'ve got an empty arraylist:
ArrayList
I think the solution from medopal is what you are looking for.
But just another alternative solution is to use a HashMap and use the key (Integer) to store positions.
This way you won't need to populate it with nulls etc initially, just stick the position and the object in the map as you go along. You can write a couple of lines at the end to convert it to a List if you need it that way.
You could also override ArrayList to insert nulls between your size and the element you want to add.
import java.util.ArrayList;
public class ArrayListAnySize<E> extends ArrayList<E>{
@Override
public void add(int index, E element){
if(index >= 0 && index <= size()){
super.add(index, element);
return;
}
int insertNulls = index - size();
for(int i = 0; i < insertNulls; i++){
super.add(null);
}
super.add(element);
}
}
Then you can add at any point in the ArrayList. For example, this main method:
public static void main(String[] args){
ArrayListAnySize<String> a = new ArrayListAnySize<>();
a.add("zero");
a.add("one");
a.add("two");
a.add(5,"five");
for(int i = 0; i < a.size(); i++){
System.out.println(i+": "+a.get(i));
}
}
yields this result from the console:
0: zero
1: one
2: two
3: null
4: null
5: five
You can use Array of objects and convert it to ArrayList-
Object[] array= new Object[10];
array[0]="1";
array[3]= "3";
array[2]="2";
array[7]="7";
List<Object> list= Arrays.asList(array);
ArrayList will be- [1, null, 2, 3, null, null, null, 7, null, null]
This is a possible solution:
list.add(list.size(), new Object());
You should set instead of add to replace existing value at index.
list.add(1, object1)
list.add(2, object3)
list.set(2, object2)
List will contain [object1,object2]
If that's the case then why don't you consider using a regular Array, initialize the capacity and put objects at the index you want.
Object[] list = new Object[10];
list[0] = object1;
list[2] = object3;
list[1] = object2;