So I made a generic list and it will only accept Strings if I cast them as (T). Here’s my code:
package dz06; import java.util.ArrayList; import java.util.List; public class Exersise04<T> { public static void main(String[] args) { new Exersise04(); } public Exersise04(){ List<T> list = new ArrayList<>(); list.add((T)"Hello"); list.add((T)25); } }
This gives me an error when I want to add the int 25 even if I cast it as (T). If it’s a generic list shouldn’t it take whatever I give it? Please help, thanks in advance
Answer
You cannot cast primitive int to (T), try cast an Integer to (T)
list.add((T)((Integer)25));
(You can cast primitive int to Integer like ((Integer)25) because of automatic boxing.)