What are some good example classes for introducing generics in Java?

I'm introducing this in the context of implementing ArrayList, but I don't want my first example to be ArrayList itself due to the inability to create arrays of a generic type. I would also like my example to be something that doesn't seem contrived/has a practical use.

  • 1
    $\begingroup$ "Implementing" ArrayList or using the library class ArrayList from Collections? $\endgroup$
    – Buffy
    Commented Oct 5, 2018 at 10:48
  • $\begingroup$ You can pretty easily do a linked list. $\endgroup$ Commented Oct 10, 2018 at 13:17
  • $\begingroup$ @ncmathsadist Definitely, but I wanted to introduce generics between array list and linked list, so that we could start off using linked lists with generics. I'm happy with the pair example mentioned below - it went over well in class. $\endgroup$ Commented Oct 10, 2018 at 13:49

1 Answer 1


While uniform collections are the obvious example, you can also build or use a Pair class in which the types of the two components are given by generic arguments. If you don't want to build it, there is a built-in class with this property: $Pair<K,V>$

But building one like it is simple enough if that is your goal.

Once you have your desired class, Write a function/method that needs to return two things instead of one. Bundle them up in a Pair.

  • $\begingroup$ Perfect! Thank you! This is a very obvious one. I suppose that's what I get for making slides at night. $\endgroup$ Commented Oct 5, 2018 at 11:07

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.