The result of the following code:
public class ListIntegerDemo1 {
    public static void addToList(List list) {list.add("0067");list.add("bb");}
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        addToList(list);
        System.out.println(list.get(0));
    }     
}
is "0067".
I would have expected a RuntimeException or similar, as I'm adding a String to an Integer List.
Why is it working without any problem?
Let's discuss certain ways in which we can perform string append operations in the list of integers. Method #1 : Using + operator + list conversion In this method, we first convert the string into a list and then perform the task of append using + operator.
So, you can use ArrayList<Either<Integer, String>> .
If you want to concatenate a string and a number, such as an integer int or a floating point float , convert the number to a string with str() and then use the + operator or += operator.
At run time, the generic type parameters are erased, so List<Integer> becomes List, and you can add any reference type to it.
If you change addToList(List list) to addToList(List<Integer> list), the compiler will prevent you from adding Strings to that list in this method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With