package edu.princeton.cs.algs4.growingtree.framework; /* KeyType.java A container class that holds a value of one of the possible key types: int, char, double. This class was created to avoid the need to store keys as Objects and cast them everywhere. */ public class KeyType implements Comparable { public static int INTTYPE = 0; public static int CHARTYPE = 1; public static int DOUBLETYPE = 2; public static int STRINGTYPE = 3; private int type; private int intval = 0; private char charval = 'a'; private double doubleval = 0.0; private String stringval = ""; public KeyType(int value) { intval = value; type = INTTYPE; } public KeyType(char value) { charval = value; type = CHARTYPE; } public KeyType(double value) { doubleval = value; type = DOUBLETYPE; } public KeyType(String value) { stringval = value; type = STRINGTYPE; } public int intValue() { return intval; } public char charValue() { return charval; } public double doubleValue() { return doubleval; } public String stringValue() { return stringval; } public boolean isInt() { return type == INTTYPE; } public boolean isChar() { return type == CHARTYPE; } public boolean isDouble() { return type == DOUBLETYPE; } public boolean isString() { return type == STRINGTYPE; } public int getType() { return type; } public String toString() { if (getType() == INTTYPE) return (new Integer(intval)).toString(); if (getType() == CHARTYPE) return (new Character(charval)).toString(); if (getType() == DOUBLETYPE) return (new Double(doubleval)).toString(); if (getType() == STRINGTYPE) return stringval; return ""; } public boolean equals(Object other) { if (this == other) return true; if (this.getClass() != other.getClass()) return false; KeyType that = (KeyType)other; if (this.getType() != that.getType()) return false; return this.compareTo(that) == 0; } public int compareTo(KeyType other) { if (getType() == INTTYPE && other.getType() == INTTYPE) return (new Integer(intval)).compareTo(other.intval); if (getType() == CHARTYPE && other.getType() == CHARTYPE) return (new Character(charval)).compareTo(other.charval); if (getType() == DOUBLETYPE && other.getType() == DOUBLETYPE) return (new Double(doubleval)).compareTo(other.doubleval); if (getType() == STRINGTYPE && other.getType() == STRINGTYPE) return stringval.compareTo(other.stringval); throw new ClassCastException(); } }