Java List toArray() Method

The toArray() method of List interface returns an array containing all the elements present in the list in proper order.

The second syntax returns an array containing all of the elements in this list where the runtime type of the returned array is that of the specified array.

Syntax

Parameters

  1. NA
  2. The parameter 'a' represents the array in which the elements of the list will be stored.

Type Parameters

The type parameter 'T' represents the component type of the array to hold the collection.

Return Value

The toArray() method returns an array that contains all the elements of this list in proper order.

Specified by

toArray() in interface Collection<E>

Throws:

ArrayStoreException- If the runtime type of the specified array is not a supertype of the runtime type of every element in this list.

NullPointerException- If the defined array is null.

Example 1

Test it Now

Output:

Alphabet :
1: a
2: b
3: c
4: d
5: e
6: f
7: g
8: h
9: i
10: j
11: k
12: l
13: m
14: n
15: o
16: p
17: q
18: r
19: s
20: t
21: u
22: v
23: w
24: x
25: y
26: z

Example 2

Test it Now

Output:

Error:(15, 22) java: bad operand types for binary operator '%'
first type:  java.lang.Object
second type: int

Operator '%' cannot be applied to java.lang.Object. If done so it will give you an error.

Example 3

This example is the solution of the above-described program.

Test it Now

Output:

List of odd numbers in our list.
1 
3 
5 
7 
9
Next TopicJava List




Latest Courses