Skip to content

Instantly share code, notes, and snippets.

@Suvink
Created May 31, 2020 13:05
Show Gist options
  • Save Suvink/50d135f08846b29a4a642987f261a442 to your computer and use it in GitHub Desktop.
Save Suvink/50d135f08846b29a4a642987f261a442 to your computer and use it in GitHub Desktop.
Java Generics
import java.util.*;
public class Mymain {
public static void main(String args[]) {
HashMap<Integer, Double> hashMapData = new HashMap<Integer, Double>();
hashMapData.put(0, 1.0);
hashMapData.put(1, 10.0);
hashMapData.put(2, 4.0);
hashMapData.put(3, 5.0);
MyMathClass<Integer, Double> mymathclass = new MyMathClass<Integer, Double>();
double result = mymathclass.Average(hashMapData);
System.out.println(result);
ArrayList resultarr = mymathclass.ConvertTo(hashMapData);
System.out.println(resultarr.toString());
}
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.lang.Number;
public class MyMathClass<T, V extends Number> {
public double Average (HashMap<T, V> hashmp){
double count = 0;
double sum = 0;
Iterator <T> i = hashmp.keySet().iterator();
while (i.hasNext()) {
int y = (int) i.next();
sum = (sum + hashmp.get(y).doubleValue());
count++;
}
double avg = sum / count;
return avg;
}
public ArrayList<V> ConvertTo(HashMap<T, V> hashmp)
{
ArrayList<V> mapValues = new ArrayList<V>(hashmp.values());
ArrayList<V> exportValues = new ArrayList<V>();
for (V temp : mapValues) {
exportValues.add(temp);
}
return exportValues;
}
}

Question

This question is based on the Collection Framework and Generics.

  • You should implement a generic class, call MyMathClass , with a type and value parameter T, V where V is a numeric object type (e.g., Integer, Double, or any class that extends java.lang.Number )

  • Implement a method named Average that takes a HashMapt of type T, V and calculate the average of the HashMap values and display. Hint: use doubleValue () method in the Number class to retrieve the value of each number as a double.

  • Implement another method call ConvertTo which convert and store HashMap values to an ArrayList. Method should takes a HashMapt of type T, V and return the ArrayList.

  • Implement a class call Mymain which having the main method and test Average and ConvertTo methods with suitable data. Your program should generate a compile-time error if your Average is invoked on a HashMap that is defined for nonnumeric elements as value parameter (e.g., <Strings, String>).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment