instanceof doesn't work for List even. for example
package org.practice;
import java.util.List;
public class InstanceOfDemo {
public static void main(String[] args) {
Employee emp1 = new Employee(1, "Ram", 10000);
Employee emp2 = new Employee(2, "Shyam", 20000);
Employee emp3 = new Employee(3, "Radha", 30000);
Object obj = List.of(emp1, emp2, emp3);
if (obj instanceof List empList) {
for (Employee emp : empList) { //Type mismatch: cannot convert from element type Object to Employee
System.out.println(emp.getId());
System.out.println(emp.getName());
System.out.println(emp.getSalary());
}
}
}
}
in the above code instanceof got true and even declared empList got created but doesn't gives any advantage to the developer because in the for loop empList can't be used without type casting as for (Employee emp : (List<Employee>)empList). And if we are doing type casting only then use type casting on obj itself like traditional code then whats the use of this feature.
Because it turns it into a raw
Listdue to type erasure in Java Generics, so you can only getObjects out of it.Since
instanceofdoesn't work with generics (runtime vs. compile-time), you can only get the erased version of any generic class, so anyFooClass<T>becomes aFooClassand you need to do an unchecked cast like in your example.