Dictionary 用TreeMap替换HashMap
我试图将代码中使用的HashMap替换为TreeMap,因为我需要对键进行排序 但是仅仅用TreeMap替换HashMap声明就遇到了以前没有出现过的各种ClassCast异常。我正在调试代码,但我无法理解为什么它失败了?它在treemap.put(key,value)中失败;声明Dictionary 用TreeMap替换HashMap,dictionary,hashmap,treemap,Dictionary,Hashmap,Treemap,我试图将代码中使用的HashMap替换为TreeMap,因为我需要对键进行排序 但是仅仅用TreeMap替换HashMap声明就遇到了以前没有出现过的各种ClassCast异常。我正在调试代码,但我无法理解为什么它失败了?它在treemap.put(key,value)中失败;声明 private static void insertIntoIndexFile(String datatype, String value, String columnName, String tableName,
private static void insertIntoIndexFile(String datatype, String value, String columnName, String tableName,
long offset) {
// TODO Auto-generated method stub
Map<Object, ArrayList<Long>> index = new TreeMap<Object, ArrayList<Long>>();
Map<Object, ArrayList<Long>> result = new TreeMap<Object, ArrayList<Long>>();
try{
String indexTableFileName = SCHEMA+"."+tableName+"."+columnName+".ndx";
File indexTableFileObject = new File(indexTableFileName);
long indexfileLength = indexTableFileObject.length();
RandomAccessFile indexTableFile = new RandomAccessFile(indexTableFileObject, "rw");
boolean isValuePresent = false;
if(indexfileLength>0){
// returns sucessfully
index = getIndexFileEntries(indexTableFileName, datatype);
// checking if the key exists
Set set1 = index.entrySet();
Iterator iterator1 = set1.iterator();
while(iterator1.hasNext()) {
Map.Entry me2 = (Map.Entry)iterator1.next();
Object key = me2.getKey();
ArrayList<Long> temp = new ArrayList<Long>();
if(key.toString().equals(value)){
System.out.println("Comparing the hashmap value to value " + key.toString());
isValuePresent = true;
temp = (ArrayList<Long>) me2.getValue();
long frequency = temp.get(0);
frequency++;
temp.set(0, frequency);
temp.add(offset);
index.put(key, temp);
break;
}
}
if(isValuePresent == false){
System.out.println("The file has values but this key was not found. Here is the updated hashmap");
ArrayList<Long> temp = new ArrayList<Long>();
temp.add(Long.parseLong("01"));
temp.add(offset);
Object key = (Object)value;
index.put(key,temp); // this line throws error
writeMapToIndexFile(tableName, columnName, datatype, index);
}else{
writeMapToIndexFile(tableName,columnName, datatype, index);
}
}catch(Exception e){
e.printStackTrace();
}
}
对于short、integer等的每种类型都有类似的stacktrace。我希望关键是这些数据类型。因此,我使用对象类型来存储键。但在插入地图之前,我并没有试图将它们转换成字符串
用treemap替换hashmap时,我忽略了什么。我同意这是一个非常广泛的问题,但任何帮助都会非常好
谢谢您的时间。您能发布您看到的异常的堆栈跟踪吗?我已经编辑了这个问题。谢谢。如果您查看
TreeMap
的源代码,很难判断没有任何代码行会发生什么。您会发现,当您将一个对象放置到一个没有比较器的树状图中时,它将调用方法compareTo
。如果键的类型不匹配,该方法可能会导致异常。我想这就是你的情况HashMap
不调用compareTo()
,因此不会导致异常!您可以尝试捕获同一类型的所有键,或者实现一个比较器
,并将其传递给新树映射(您的比较器)
java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.String
at java.lang.String.compareTo(Unknown Source)
at java.util.TreeMap.put(Unknown Source)
at Database.insertIntoIndexFile(Database.java:433)
at Database.insertIntoTable(Database.java:369)
at Database.main(Database.java:1340)