How Dynamic Lists Work — API Cheat Sheet
No exercise here — Java's ArrayList and C#'s List<T> side by side, the two languages here with a resizable-list type distinct from a raw array.
This is a reference page, not a graded exercise.
In Python and JavaScript/TypeScript, "array" and "list" are the same built-in type — see the Arrays cheat sheet for list/Array methods like .append/.push. Java and C# are different: their raw arrays (int[], T[]) are fixed-size, so when you need to grow or shrink a collection you reach for a separate generic class — ArrayList<T> in Java, List<T> in C#. This page is about those two.
Java — ArrayList<T>
| Want to... | Method | Example |
|---|---|---|
| Create | new ArrayList<>() | List<Integer> list = new ArrayList<>(); |
| Add to the end | .add(v) | list.add(5); |
| Add at an index | .add(i, v) | list.add(0, 5); (shifts everything right) |
| Read/write an index | .get(i) / .set(i, v) | there's no [] indexing on ArrayList, unlike a raw array |
| Remove by index | .remove(i) | takes an int |
| Remove by value | .remove(Object o) | careful: list.remove(5) on a List<Integer> removes index 5, not the value — use list.remove(Integer.valueOf(5)) to remove the value |
| Check membership | .contains(v) | list.contains(5) |
| Find an index | .indexOf(v) | -1 if missing |
| Size | .size() | not .length and not .length() |
| Sort | Collections.sort(list) | or list.sort(Comparator...) |
| Iterate | for-each | for (int x : list) { ... } |
C# — List<T>
| Want to... | Method | Example |
|---|---|---|
| Create | new List<T>() | var list = new List<int>(); |
| Add to the end | .Add(v) | list.Add(5); |
| Add at an index | .Insert(i, v) | list.Insert(0, 5); |
| Read/write an index | indexer [] | list[0] = 5; — unlike Java, C#'s List<T> does support [] |
| Remove by index | .RemoveAt(i) | takes an int |
| Remove by value | .Remove(v) | removes the first matching value |
| Check membership | .Contains(v) | list.Contains(5) |
| Find an index | .IndexOf(v) | -1 if missing |
| Size | .Count | property, not a method — no parens |
| Sort | .Sort() | in place |
| Iterate | foreach | foreach (var x in list) { ... } |
The gotcha that catches almost everyone coming from Python/JS: Java's ArrayList has no [] operator at all — it's .get(i)/.set(i, v) only. And list.remove(5) on a List<Integer> is ambiguous-looking but not ambiguous to the compiler: it always resolves to the int (index) overload unless you box the argument yourself.
Hints
Companies
No companies reported yet.
Discussion
Sign in to join the discussion.
Loading discussion...
Test results
This question doesn't have a code exercise.