Hello, I would like to know if there are convenient ways to resort a treeMap, there is my failed
testing code:
////////////////////////////////////////////////////////////
import java.util.TreeMap;
public class SortedKey implements Comparable {
public static Object sortType = "name";
public
String key;
public String name;
public String type;
public static void main(String[] args) {
TreeMap tm = new TreeMap();
tm.put(new SortedKey("k1", "T", "C"), "1");
tm.put(new SortedKey("k2", "A", "D"), "2");
tm.put(new SortedKey("k3", "H", "Z"), "3");
tm.put(new SortedKey("k4", "Z", "A"), "4");
//try re-sort ! //
SortedKey.sortType = "name";
System.out.println(tm.entrySet()); //our=[k1=1, k2=2, k3=3, k4=4]
SortedKey.sortType = "key";
System.out.println(tm.entrySet()); //our=[k1=1, k2=2, k3=3, k4=4]
SortedKey.sortType = "type";
System.out.println(tm.entrySet()); //our=[k1=1, k2=2, k3=3, k4=4]
// ---------- //
}
public int compareTo(Object arg0) {
SortedKey tmp = (SortedKey) arg0;
if (sortType.toString() == "key")
return (this.key.compareTo(tmp.key));
else if (sortType.toString() == "name")
return (this.name.compareTo(tmp.name));
else
return (this.type.compareTo(tmp.type));
}
public SortedKey(String name, String key, String type) {
this.name = name;
this.key = key;
this.type = type;
}
public String toString() {
return name;
}
}
////////////////////////////////////////////////////////////
any idea ?