For one of the Homeworks in my class, we have a collection of a class titled Pair and we need to sort it in ascending order based on the value of the key.
I could apply this if the keys were strings or integers, but how do I write code that would compare my items when they're Generic as seen below?
The professor in my class explained what to do for integers or strings but when my variables are generic I'm at a complete loss.
Below are copies of the relevant parts of my code.
import java.util.*;
public class Utils {
public static<K extends Comparable<K>, V> Collection<Pair<K,V>> sortPairCollection(Collection <Pair<K,V>> col){
ArrayList <Pair<K,V>> list = new ArrayList<>();
//Code to compare
return list;
}
public static void main(String[] args) {
ArrayList <Pair<String,Integer>> list = new ArrayList<>();
Pair<String, Integer> e = new Pair<>("One", 1);
list.add(e);
Pair<String, Integer> f = new Pair<>("Two", 2);
list.add(f);
Utils help = new Utils();
help.sortPairCollection(list);
}
}
This second part here is the code for my Pair class. import java.io.Serializable; import java.util.Objects;
public class Pair <K,V> extends Object implements Serializable, Cloneable{
public Pair(K k, V v){
this.k = k;
this.v = v;
}
public K k(){
return k;
}
public V v(){
return v;
}
/*
... //irrelevant data omitted
*/
private final K k;
private final V v;
}
<K extends Comparable<K>, V>. What you need to do is use thecompareTomethod ofComparable.