Home > database >  How to get ArrayList Type and create an ArrayList based off that?
How to get ArrayList Type and create an ArrayList based off that?

Time:12-20

I have this method to read a txt file. First it converts the .txt file to an Object, and then checks if it's an ArrayList. If it is I want to create an ArrayList of whatever type obj is.

    public static readFile(String fileName) {
        Object obj = null;
        
        try {
            obj = deserialize(fileName);
        } catch (IOException e) {
            return null;
        } catch (ClassNotFoundException e) {
            return null;
        }

        ArrayList<?> list;

        if (obj instanceof ArrayList<?>) {
            list = (ArrayList<?>) obj;
        } else {
            return null;
        }

        return null;
    }

I know all elements of the ArrayList will be of the same type in my scenario so I was thinking about using list.get(0).getClass() I tried doing ArrayList<(list.get(0).getClass()> but it doesn't work so I don't know where to go from here.

CodePudding user response:

I was thinking about using list.get(0).getClass() I tried doing ArrayList<(list.get(0).getClass()>

Generics is a compile time mechanism. Its purpose is to allow the compiler to verify that manipulations in your code are type-safe.

And during the compilation ArrayList<Something> turn into ArrayList<Object>, this process is called generic type erasure.

You can't provide a generic type through a method call, like list.get(0).getClass().

If you want to benefit from generics, then you need to provide the Generic type explicitly, and can't be dynamic.

CodePudding user response:

You can't do that!

Think about that, if you can do that, it same to this:

ArrayList<Integer> instanceof ArrayList<?> or ArrayList<Integer> instanceof ArrayList<Number>

Integer is a Number, that is ok, but as generics is invariance, ArrayList<Integer> is not a ArrayList<Number>. This contradicts the above.

  • Related