Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding String to List<Integer>

Tags:

java

generics

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?

like image 529
ken Avatar asked Apr 28 '15 13:04

ken


People also ask

Can we add string to a integer list?

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.

Can we add string and int in ArrayList?

So, you can use ArrayList<Either<Integer, String>> .

How do you add a string and integer to a list in Python?

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.


1 Answers

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.

like image 59
Eran Avatar answered Oct 16 '22 11:10

Eran