This is a two part assignment, i've completed part 1 but part 2 is kicking my butt because i missed that class. I will provide the part 1 code. Please leave comments so i can maybe follow along and understand what is going on in this part.
public class KeyValuePair { private K key; private V value; /** * @param key * @param value */ public KeyValuePair(K key, V value) { this.key = key; this.value = value; } public K getKey() { return key; } public void setKey(K key) { this.key = key; } public V getValue() { return value; } public void setValue(V value) { this.value = value; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; KeyValuePair other = (KeyValuePair) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; return true; } @Override public String toString() { return "("+ key +"," + value +")"; } }
public class PairApp {
public static void main(String[] args) { KeyValuePair p1 = new KeyValuePair("SLC", 189899); KeyValuePair p2 = new KeyValuePair("NY", 8244910); System.out.println("p1:" + p1); System.out.println("p2"+ p2); System.out.println("p1.equals p(2): " + p1.equals(p2)); p1 = p2; System.out.println(); System.out.println("p1: " + p1); System.out.println("p2: " + p2); System.out.println("p1.equals(p2): "+p1.equals(p2)); } }
Lab Key Value Pair
Part 2 Description: output: Implement the interface Comparable SF 812826 another? SLC: 189899 For our implementation we say that an instance of a KeyvaluePait interface. In that case we could just use the compareTo method of K to find out whether a key valu is smaller or greater To allow us to do that we wi ill modify class KeyValuePai so that it restricts the possible types that can be used as a type argument for K. We will only allow types that implement Comparable How can that be done? Change the unbounded type parameter Kin Key ValuePair to a bounded type paramete K extends Comparable V The header of your class declarations should look now like this public class KeyValuePair> Notice that you specify the restriction on type K only once when you first introduce the type parameter Now you are ready to implement the method compareTo Make sure that two KeyValuePairs are greater smaller based on the value of the key. In main do the following: Create 2 more KeyValuePairs for LA 3819702 SF 812826 Create a generic List, call it cities, and initialize it with the 4 KeyvaluePairs that we have created Print the list-one item per line (label the output) he lis Sort t Print the now so d list -one item per line rte