0

I am wondering if ya'll can help me get a better grip on generics. I have simplified this question as much as possible.

I am trying to save the element stored in a linked list in a variable called saveIt. I know LinkedList itself uses generics, so I want my variable to take up whatever data type is in the list. I believe LinkedList itself designates that type as E, but when I try to declare a variable as 'E saveIt' I get "cannot resolve symbol E."

public class Main {
    public static void main(String[] args) {
        // whatever goes here ...
    }

    void saveElement(LinkedList input) {
        E saveIt = input.getFirst();
    }
}

If I make the LinkedList then I can declare a variable as 'Integer saveIt' but that isn't what I want to do.

public class Main {
    public static void main(String[] args) {
        // whatever goes here ...
    }

    void saveElement(LinkedList<Integer> input) {
        Integer saveIt = input.getFirst();
    }
}

I considered declaring 'Object saveIt' but I'm not sure whether that is the right approach. The concept of datatype E obviously exists in Java, and isn't quite the same as Object (or is it?), so why can't I access it (or how can I access it)?

public class Main {

    public static void main(String[] args) {
        // whatever goes here ...
    }

    void saveElement(LinkedList input) {
        Object saveIt = input.getFirst();
    }
}

So, basic question is if I want to have my method address whatever datatype is in the list, how do I do that?

1 Answer 1

1
<E> void saveElement(LinkedList<E> input) {
    E saveIt = input.getFirst();
}

You need to tell Java that E is a type parameter of your method -- it's like another thing that's being passed in! -- and that the LinkedList contains elements of type E.

Sign up to request clarification or add additional context in comments.

3 Comments

Seriously?! Wow. That was easy (I did search quite a while before asking--maybe it's just supposed to be obvious). Thanks.
this is equivalent to just void saveElement(LinkedList<?> input)
Depends what else gets done with the value and if the rest of the code needs to mention E. I assumed this wasn't the OP's complete code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.