Example 1 — Add a Forgotten Layer to a Suitcase
A suitcase is packed bottom-up; the sweater was forgotten and belongs between the jeans and the shirts.
import java.util.Stack;
public class StackInsertElementAtDemo {
public static void main(String[] args) {
Stack<String> suitcase = new Stack<>();
suitcase.push("shoes");
suitcase.push("jeans");
suitcase.push("shirts");
suitcase.insertElementAt("sweater", 2);
System.out.println("layers: " + suitcase);
System.out.println("sweater at index " + suitcase.indexOf("sweater"));
System.out.println("still on top: " + suitcase.peek());
}
} How It Works
- Element first, index second.
insertElementAt("sweater", 2)names the item and then the layer it should occupy. - Upper layers move up. shirts was at index 2 and moves to 3; shoes and jeans below are not touched.
- Top unchanged. Because index 2 is below the top,
peek()still returns shirts.

