+ 5
Why this code gives error
Here Teacher is parent of Student List<Student> list = new ArrayList<>(); List<Teacher> list1 = list; // But this code works like a charm List<Student> list = new ArrayList<>(); List<Teacher> list1 = new ArrayList<>(); list1.addAll(list); Please explain it to me. Please do not provide any link
6 odpowiedzi
+ 3
Thanks but this is not what i want
+ 3
I am just trying to know why this code gives error
+ 2
I doubt if we can directly refer it like that without actually creating an instance of it. You can try this and let me know if it worked or not. Just an opinion.
List<Teacher> list1 = new ArrayList<>(list);
OR
List<Teacher> list1 = new ArrayList<>();
list1 = list;
+ 2
If you can share a little bit more on what actually you are trying to achieve then probably it would be helpful for others to answer.
0
I think its giving an error because you havent specified the type of list whether its an integer or string
0
Hello Sumit Programmer😎😎
Upcasting treats your list as List but the object is still an ArrayList.
You can not just convert a List into an ArrayList.
I am not completely sure but:
List<Student> list = new ArrayList<>()
-> upcast works automatically
But in here you need to cast manually:
List<Teach> list1 = (ArrayList) list;