Date: 2012may3
Update: 2025oct3
Language: Java
Keywords: append, prepend, push
Q. Java: Prepend (add at the start) an element to a ArrayList
A. Use add() with 0 as the first parameter (the position).
iAs shown in this full example:
import java.util.ArrayList;
class Demo {
static void prepend(ArrayList<String> list, final String first) {
list.add(0, first);
}
public static final void main(String[] args) {
ArrayList<String> a = new ArrayList<String>();
a.add("one");
a.add("two");
a.add("three");
prepend(a, "Top");
for (int i = 0; i < a.size(); i++) {
System.out.println(i + "=" + a.get(i));
}
}
}
Output:
0=Top
1=one
2=two
3=three