1

I am learning about generics so I made a simple java program so I can learn how they exactly work. But now I am stuck with this program because I can't see why it won't work.

public static void main(String[] args)
    {
        ArrayList<String> strings = new ArrayList<>();
        strings.add("A");
        strings.add("B");

        printList(strings);
    }

    public static <E extends List<E>> void printList(ArrayList<E> l)
    {
        for (E obj : l)
        {
            System.out.println(obj.toString());
        }
    }
4
  • Why is E required to extend List<E>? Commented Jun 18, 2018 at 18:32
  • Because you've specified E to extend List<E>. Which is not true for String. Commented Jun 18, 2018 at 18:33
  • Your formal argument is effectively ArrayList<? extends List<E>>. Either replace the parameter type with E, or drop the bound on E. Commented Jun 18, 2018 at 18:33
  • What you've specified with your method generics is that the argument passed to the method will be an ArrayList<List<E>>. A list of lists, basically. Then you pass it a list of String. Just take out the <E extends List<E>> part and you should be good to go. Commented Jun 18, 2018 at 18:36

2 Answers 2

6

<E extends List<E>> is almost certainly not what you want. What that says is that your element type is a list of itself.

Instead, write just <E>.

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

Comments

5

Your generic parameter E should not extend list. if E extends List<E> then you should be expecting List< List<> >.

Your method should look something like:

public static <E> void printList(List<E> list) {

    for (E obj : list) {

        System.out.println(obj);
    }
}

Notes:

  • Use meaningful argument names like list not l so that code maintainers understand your code

  • System.out.println(object.toString()) can be simplified to System.out.println(object) because toString() will be called automatically

  • If you want you code to be more robust, make the parameter a List<E> so you can accept all List<E> objects such as LinkedList<E> and all other implementations.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.