SE251Ex:Generic Pair

From Marks Wiki
Revision as of 05:21, 3 November 2008 by Mark (talk | contribs) (8 revision(s))
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Writing a generic Pair

Description

One of the drawbacks of Java is there isn't an easy way to return multiple values from a method. It would be nice to return say a pair of values, each with a specifiable type. So, for this exercise, you are to write a generic Pair class to hold two objects of parameterisable types. For example, a variable of type Pair<String,Date> will hold a String object and a Date object. It should define/override the following public methods:

  • T1 getFirst() - access the first element of the pair
  • void setFirst(T1) - update the first element of the pair, where T1 is the type variable for the first element
  • T2 getSecond() - access the second element of the pair
  • void setFirst(T2) - update the second element of the pair, where T2 is the type variable for the second element
  • int hashCode() - returns the sum of the hashCodes of the elements. I.e. returns first.hashCode() + second.hashCode(). The reason for overriding this is a little tricky. It's mainly for our Pair to work nicely with HashSets and HashMaps.
  • boolean equals(Object) - returns true if and only if the given Object is instace of Pair and the individual elements of this Pair are equal to the respective elements of the given Pair
  • String toString() - returns the String representation of the pair in the form of "<first, second>"

Below is an example of how we can benefit from your Pair class:

public static void main(String[] args) {
   int[] nums = {1,4,2,4,3,4,9,8,7,6,6,2};
   Pair<Integer,Double> result = medianAndMean(nums);
   System.out.println("Median & Mean: "+result);
   
   int[] nums2 = {6,4,2,3,5,9,2,8,3};
   Pair<Integer,Double> result2 = medianAndMean(nums);
   System.out.println("Same? " + result.equals(result2));
}

public static Pair<Integer,Double> medianAndMean(int[] numbers) {
   Integer median = calculateMedian(numbers); //assume this method exists
   Double mean = calculateMean(numbers); //assume this method exists
   return new Pair<Integer,Double>(median,mean);
}

And the corresponding output:

Median & Mean: <4, 4.6667>
Same? true

Test Cases

  • Use TestPair to test the correctness of your Pair

Tips

If you're still not friendly with generics, first write a non-generic Pair that stores both its items as Objects. Then pretty much replace every occurrence of Object with the appropriate type variable.

Discussion

Here you can ask questions and discuss stuff