Commit 52b97af
committed
feat(ListDemo4): demonstrate List to array conversion and sorting
What
- Added ListDemo4 example.
- Showed two ways to convert a `List<Integer>` to arrays:
1. `toArray()` → returns `Object[]`.
2. `toArray(new Integer[0])` → returns a typed `Integer[]`.
- Printed the array reference (default `toString()` prints memory address).
- Sorted the list using `Collections.sort()` and printed the result.
Why
- Clarifies difference between `toArray()` overloads.
- Shows best practice: using `toArray(new Integer[0])` for type safety.
- Reinforces usage of `Collections.sort()` for natural ordering.
How
- Create `ArrayList<Integer>` with elements [5,1,2,3].
- Convert list to `Object[]` and `Integer[]`.
- Print `array1` (prints reference, not values).
- Sort list ascending → [1,2,3,5].
- Print sorted list.
Logic
- `Object[] array = list.toArray();`
- Produces a generic array of type Object[].
- `Integer[] array1 = list.toArray(new Integer[0]);`
- Produces a strongly typed Integer[].
- Common idiom: passing zero-length array ensures correct type.
- Sorting:
- `Collections.sort(list);` → O(n log n) using TimSort.
- Natural ordering: ascending for integers.
Real-life applications
- Exporting collections to arrays for interoperability with legacy APIs.
- Ensuring type safety when working with arrays from generics.
- Sorting lists in-place for display, storage, or computation.
Notes
- Printing an array directly (`System.out.println(array1)`) prints its memory address.
Use `Arrays.toString(array1)` for human-readable output.
- `Collections.sort(list)` modifies list in place.
- Since Java 8, you can also use `list.sort(null)` for natural ordering.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent b7317e3 commit 52b97af
File tree
1 file changed
+23
-0
lines changed- Section 25 Collections Frameworks/List Interface/ArrayList/src
1 file changed
+23
-0
lines changedLines changed: 23 additions & 0 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
0 commit comments