Commit a06a4af
committed
feat(ListDemo1): add demo of converting List to arrays (Object[] and typed Integer[])
What
- Added ListDemo1 class.
- Created a List<Integer> with values [1,2,3].
- Demonstrated two methods of converting List to array:
- toArray() → returns Object[].
- toArray(new Integer[0]) → returns typed Integer[].
- Printed both arrays to verify conversion.
Why
- Highlights difference between raw toArray() and generic toArray(T[]).
- Shows why using toArray(new T[0]) is preferred to avoid casting from Object[].
- Provides a clear example of converting a generic collection to arrays.
How
- list = [1,2,3].
- Object[] objectArray = list.toArray():
- Produces array of type Object[].
- Iterated and printed as Objects.
- Integer[] integerArray = list.toArray(new Integer[0]):
- Produces array of type Integer[].
- Iterated and printed as Integers.
Logic
- Inputs: integers added to ArrayList.
- Outputs: elements printed from both Object[] and Integer[] arrays.
- Flow:
1. Create list and add elements.
2. Convert to Object[] via toArray().
3. Iterate and print.
4. Convert to Integer[] via toArray(new Integer[0]).
5. Iterate and print.
- Edge cases:
- toArray() returns Object[] → requires explicit casting if assigning to specific type.
- toArray(new Integer[size]) also works (slightly faster than new Integer[0]).
- Complexity: O(n) copy for toArray().
- Concurrency: not thread-safe.
Real-life applications
- Converting lists into arrays for APIs that require arrays (e.g., legacy libraries, JDBC batch parameters).
- Typed array conversions useful for serialization, reflection, or exporting data.
- Object[] variant useful when type safety not required.
Notes
- Best practice is to use toArray(new T[0]) to get strongly-typed arrays.
- In Java 11+, toArray(IntFunction<T[]>) is available for even more concise conversions.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 4dabc3d commit a06a4af
File tree
1 file changed
+33
-0
lines changed- Section 25 Collections Frameworks/List Interface/ArrayList/src
1 file changed
+33
-0
lines changedLines changed: 33 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 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
| 33 | + | |
0 commit comments