Skip to content

Commit 52b97af

Browse files
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 changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import java.util.ArrayList;
2+
import java.util.Collections;
3+
import java.util.List;
4+
5+
public class ListDemo4 {
6+
public static void main(String[] args) {
7+
List<Integer> list = new ArrayList<>();
8+
9+
list.add(5);
10+
list.add(1);
11+
list.add(2);
12+
list.add(3);
13+
14+
// List to array.
15+
Object[] array = list.toArray();
16+
Integer[] array1 = list.toArray(new Integer[0]); // Zero Size Ki Array.
17+
System.out.println(array1);
18+
19+
// Sort the list.
20+
Collections.sort(list);
21+
System.out.println(list);
22+
}
23+
}

0 commit comments

Comments
 (0)