0

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.

Akash Kumar
  • 642
  • 7
  • 20
  • 1
    Generics are a compiler feature; at runtime, generics do not exist. If you try `longList = (List) stringList`, it'll fail because the compiler knows `stringList` is a `List`. But since you assigned `stringList` to an `Object` variable, and casted the `Object` instead, the program is now depending on `ClassCastException` to catch the issue. But due to type erasure, all the lists are [raw](https://docs.oracle.com/javase/tutorial/java/generics/rawTypes.html) `List`, without type information, and casting a `List` to a `List` is fine. – Vince Dec 05 '19 at 05:59
  • 1
    Possible duplicate of [Type safety: Unchecked cast](https://stackoverflow.com/q/262367/5221149) – Andreas Dec 05 '19 at 06:15
  • Possible duplicate of [What is unchecked cast and how do I check it?](https://stackoverflow.com/q/2693180/5221149) – Andreas Dec 05 '19 at 06:16
  • 1
    *"Why is it behaving so?"* Because you're ignoring the `Type safety: Unchecked cast from Object to List` **warning** on the following code: `(List) abcList` --- The warning is telling you that Java's normal type-safety is being bypassed, and that what you're doing may cause unexpected results if the `Object` is not actually a `List`. Ignore warning at your own peril. – Andreas Dec 05 '19 at 06:18

0 Answers0