4
$\begingroup$

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.

$\endgroup$
3
  • 1
    $\begingroup$ "Implementing" ArrayList or using the library class ArrayList from Collections? $\endgroup$
    – Buffy
    Oct 5, 2018 at 10:48
  • $\begingroup$ You can pretty easily do a linked list. $\endgroup$ 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$ Oct 10, 2018 at 13:49

1 Answer 1

3
$\begingroup$

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.

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

Your Answer

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

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