Generics


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


Part A

(remember to use Integer, Double, Boolean, not int, double, boolean when creating/using generics)

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 (not ArrayList) of any type and prints it in reverse order. Test it with an array of ints and then with one of Strings.

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 Ninjas and an array of Strings, and show in main 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 Ninja n = chooseRandom(arrayOfNinjas); and then have that ninja assassinate. (note that the toStrings on these particular example classes will not give you very useful info, you may adjust them if you prefer).

Write a generic method fight with a type parameter bounded to Fighter. It should take two parameters of the same bounded type. Have the first attack and the second defend, then the first defend and the second attack, and then randomly (50/50 chance) return either the first or the second . When you call it in main, 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 MyPair's first two parameters) but adds a third element. Give it a third instance variable using the new type. Add at least a parameterized constructor that takes arguments for all three and update the toString to 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 MyTriple objects with different types (not all three types for each have to be different) and make sure printing works.