Skip to content

Commit 8e0985f

Browse files
committed
BAEL-2024 : java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList : Kirti Deo
1 parent 7beadb7 commit 8e0985f

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package com.baeldung.classcastexception;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.List;
6+
7+
public class ClassCastException {
8+
9+
public static void main(String[] args) {
10+
11+
List<ArrayList<Person>> personList = new ArrayList<ArrayList<Person>>();
12+
// To correct the Exception at line #18, modify the line #11 code as:
13+
// List<List<Person>> personList = new ArrayList <List<Person>>();
14+
// Line #18 code as personList.add(Arrays.asList(personArray));
15+
Person p1 = new Person(1, "John");
16+
Person p2 = new Person(2, "Snow");
17+
Person[] personArray = new Person[] { p1, p2 };
18+
personList.add((ArrayList<Person>) Arrays.asList(personArray));
19+
System.out.println("Personlist: " + personList);
20+
21+
}
22+
23+
}
24+
25+
class Person {
26+
int id;
27+
String name;
28+
29+
Person(int id, String name) {
30+
this.id = id;
31+
this.name = name;
32+
}
33+
34+
@Override
35+
public String toString() {
36+
return "Person [id=" + id + ", name=" + name + "]";
37+
}
38+
39+
}

0 commit comments

Comments
 (0)