Generics & Collections


Namey.java
Fighter.java
Ninja.java
Bee.java
MyPair.java Generic, inherits from Namey
Coordinate.java inherits from MyPair < Integer,Integer>
GenericExample.java

Java API

ArrayList
HCCClass.java
ClassCreditComparator.java
ArrayListExample.java

Generics and Collections notes

read ch 20, 21, 11


Practice


Part A

Add Namey, MyPair, Fighter, Bee, and Ninja to your project.

In a class with a main, write a generic method printBackward which takes an array of any type and prints it in reverse order. Test it with an array of ints and then with one of Bees (remember to use Integer, Double, Boolean, not int, double, boolean).

Write a generic method chooseRandom, which takes an array of any type and returns a randomly chosen element of the array. Test it with an array of  Bees and an array of Strings, and check that when you give it an array of a certain type, you don't have to cast to get that type back (e.g. you can do Bee b = chooseRandom(arrayOfBees);)

Write a generic method fight with a type parameter bounded to Fighter.  It should take two parameters of the bounded type.  Have the first attack and the second defend, then the first defend and the second attack, and then return either the first or the second (50/50 chance).  Check that when you pass this method two Ninjas you get back a Ninja who can assassinate and when you pass fight two Bees you get back a Bee who can sting, without having to do any casting.


Part B

Create a generic class MyTriple with 3 type parameters that inherits from MyPair (using the first two parameters)  and adding a third element, using the third.  The toString should follow the same pattern as the one for MyPair, but with all three elements in the parens.

In a main, create at least two different Triple objects with different types (not all three types for each have to be different) and make sure printing works.