+ 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

3rd Apr 2020, 9:34 AM
Sumit Programmer😎😎
Sumit Programmer😎😎 - avatar
6 odpowiedzi
+ 3
Thanks but this is not what i want
3rd Apr 2020, 12:06 PM
Sumit Programmer😎😎
Sumit Programmer😎😎 - avatar
+ 3
I am just trying to know why this code gives error
3rd Apr 2020, 5:01 PM
Sumit Programmer😎😎
Sumit Programmer😎😎 - avatar
+ 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;
3rd Apr 2020, 10:01 AM
Avinesh
Avinesh - avatar
+ 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.
3rd Apr 2020, 1:59 PM
Avinesh
Avinesh - avatar
0
I think its giving an error because you havent specified the type of list whether its an integer or string
4th Apr 2020, 4:40 PM
rachel oyugi
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;
21st Apr 2020, 2:14 PM
Denise Roßberg
Denise Roßberg - avatar