- Get familiar with generic types Given the following class
public class MyPair<T, U> { public final T Fst; public final U Snd;
public MyPair(T fst, U snd) { this.Fst = fst; this.Snd = snd;
}
public String toString() { return ( + Fst + , + Snd + ); }
}
- In a new source file, write a program that includes this declaration and also a class with an empty Main method. Compile it to check that the program is well-formed.
- Declare a variable of type MyPair<String, Integer> and create some values, for instance new MyPair<String, Integer>(Anders, 13), and assign them to the variable.
- Declare a variable of type MyPair<String, Double>. Create a value such as new MyPair<String, Double>(Phoenix, 39.7) and assign it to the variable.
- Can you assign a value of type MyPair<String, Double> to a variable of type MyPair<String, Integer>? Should this be allowed?
- Declare a variable grades of type MyPair<String, Integer>[], create an array of length 5 with element type MyPair and assign it to the variable. Create a few MyPairs and store them into grades[0], grades[1] and grades[2].
- Use the foreach statement to iterate over grades and print all its elements. What are the values of those array elements you did not assign anything to?
- Declare a variable appointment of type
MyPair<MyPair<Integer, Integer>, String>
and create a value of this type and assign it to the variable.
What is the type of appointment.Fst.Snd? This shows that a type argument may itself be a constructed type.
- Declare a method Swap() in MyPair<T, U> that returns a new value of type MyPair in which the components have been swapped.
- Differences between Object, generic and generic raw types
In JAVA, there is a Map data structure that helps developers to link a key to a value.
Read about Map in
- https://www.geeksforgeeks.org/mapinterfacejavaexamples/
- https://www.geeksforgeeks.org/javautilhashmapinjava/
- https://www.tutorialspoint.com/java/java_hashmap_class.htm
As we want to reimplement the Map class, implement a class named MyMap to manage (store and get back) any object by its ID.
- User can put an object obj to a Map m by calling
m.put(obj.getID(), obj);
- User can get back an object from the map m by invoking
m.get(id);
- Implement the MyMap in two different ways:
- Use Object as the type for both the Key and the Value parameters of the put and get methods
- Use generic type
- With your implementations, write a main function to
- Test these two implementations
- To show advantage of generic type over Object
- To show advantage of parameterized type over generic raw type
Reference: textbook Java How to Program, chapter 20
Reviews
There are no reviews yet.