Since JAVA is a strict type language, Ideally a variable of Integer type can only store or refer to Integer type only. But, In this case a variable of Type List is assigned List, how is it possible?
import java.util.*;
public class Main
{
public static void main(String[] args) {
//Defining 2 Lists
List<Long> longList = new ArrayList<>();
List<String> stringList = new ArrayList<>();
//Initialising list of string
stringList.add("1");
stringList.add("abc");
stringList.add("2");
//Initialising variable of object type with list of stirng
Object abcList = stringList;
//Casting Object which is List of String to List Of Long
longList = (List<Long>) abcList;
//Checking values in List of Long
if(longList.contains("abc")){ //TRUE
System.out.println("Yes String exist in String Of Long - \n");
}
if(longList.contains(1L)){ //FALSE
System.out.println("Long exist in List Of Long - \n");
}
}
}
This program is giving output as "Yes String exists in String Of Long". Why is it behaving so? I can't find a reasonable explaination.