Oktavix
Oktavix

Reputation: 151

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

            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

Upvotes: 1

Views: 1630

Answers (4)

kevin ternet
kevin ternet

Reputation: 4612

you just have to declare a List of Objects (the mother of all objects)

List<Object> list = new ArrayList<Object>();
list.add((T)"Hello");
list.add((T)25);

Upvotes: 0

The reason of you error is because you are implementing in a bad way the generic class...

if you are coding in a good IDE, the you should at least get a warning, something like

Exersise04 is a raw type. References to generic type Exersise04 should be parameterized

This is because, you defined the class generic, but then you are implementing it like:

public static void main(String[] args) {
    new Exersise04();
}

which means, Exersise04 has no idea what is holding at the time it was declarated...(not good, bad practice)

try doing instead

public class Exersise04<T> {

    public static void main(String[] args) {
    new Exersise04<String>();
    }

    public Exersise04() {
    List<T> list = new ArrayList<>();
    list.add((T) "Hello");
    list.add((T) 25);
    }
}

and then you will see that your compiler will complain here list.add((T) 25); because now we all are sure, that this class is only holding allowing String objects

Cannot cast from int to T

Upvotes: 0

ksr78
ksr78

Reputation: 1

I think you're misunderstanding the 'generic' part of your list. You're thinking of it is as a list plain objects, which it is not. It is a list of 'T' objects, where T is a generic parameter to your Exercise04 class.

I you want to store a list of 'stuff', like strings and integers, you need to use List<Object>.

To put integers in a list, you can do:

List<Integer> iList = new ArrayList<>();
list.add(100);

which works because of boxing. However you can't then put strings in.

Otherwise, the 'T' your case would be defined by someone instantiating your Exercise04 class.

Upvotes: 0

waltersu
waltersu

Reputation: 1231

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.)

Upvotes: 2

Related Questions