How do I put numbers in a generic list?

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<>();




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


You cannot cast primitive int to (T), try cast an Integer to (T)


(You can cast primitive int to Integer like ((Integer)25) because of automatic boxing.)

Leave a Reply

Your email address will not be published. Required fields are marked *