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 Oct 5 '18 at 10:48
  • $\begingroup$ You can pretty easily do a linked list. $\endgroup$ – ncmathsadist Oct 10 '18 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$ – cryptic_star Oct 10 '18 at 13:49

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$ – cryptic_star Oct 5 '18 at 11:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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