java - 当我调用 hashTable.get(key) 时获取 null

标签 java hashtable

我的项目中有 Pair 类,并且我在应用程序中使用哈希表。 构建哈希表后,我通过打印哈希的内容来测试 Pair 对象是否已创建并正确存储在哈希表中,并且我立即尝试使用 get(key) 方法获取其中一个值,它总是给出我为空。

这是我的整个类,映射,它有一个哈希表类型的私有(private)对象 包元存储;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.StringTokenizer;
import org.apache.hadoop.hive.ql.parse.ASTNode;
import preprocessingQuery.Pair;

public class Mapping {
private Hashtable<Pair, Pair> hashTable ;

public Mapping(){
    hashTable= new Hashtable<Pair, Pair>();
}


public Hashtable<Pair, Pair> getHashTable() {
    return hashTable;
}


public void setHashTable(Hashtable<Pair, Pair> hashTable) {
    this.hashTable = hashTable;
}


public Pair getMapping( Pair originalPair) {
    Pair mappedPair=(hashTable.get(originalPair));
    return mappedPair;
}
public ArrayList<Mapping> getPairs(ASTNode an){
    ArrayList<Mapping> pairs=new ArrayList<Mapping>();
    return pairs;
}

public void print() {
    Enumeration<Pair> contentOfHT;
    contentOfHT = hashTable.keys(); 
    while(contentOfHT.hasMoreElements()) { 
    Object str =  contentOfHT.nextElement(); 
    System.out.println(str + "\tis mapped to " + 
            hashTable.get(str)); 
    } 
}


public void loadMappingTable() {
    String originalTable;
    String originalCol;
    String mappedTable;
    String mappedCol;
    Pair originalPair;
    Pair mappedPair;
    BufferedReader in = null;

    try {
        in = new BufferedReader(
                new FileReader(
                        "D:\\Documents and Settings\\QUAdmin.STAFF\\Desktop\\mapping.txt"));
        String line ;
        while ((line = in.readLine()) != null) {
            StringTokenizer stok = new StringTokenizer(line, "\t");
            originalTable= stok.nextToken();
            originalCol= stok.nextToken();
            mappedTable= stok.nextToken();
            mappedCol= stok.nextToken();
            originalPair=new Pair(originalTable,originalCol);
            mappedPair=new Pair(mappedTable,mappedCol);
            hashTable.put(originalPair, mappedPair);

        }
    } catch (Exception ex) {
        // catch all exceptions as one. This is bad form imho
        ex.printStackTrace();
    } finally {
        try {
            if (in != null)
                in.close();
        } catch (IOException ex) {
        }
    }
}

public static void main(String[] args)
{
    Mapping map=new Mapping();
    map.loadMappingTable();
    System.out.println("Size: "+ map.getHashTable().size());

    System.out.println("The content of the hash table");
    map.print();
    System.out.println("Testing the mapping");
    Pair originalPair=new Pair("table1","table1_name");
    System.out.println(map.getMapping(originalPair));
    System.out.println(map.getHashTable().get(originalPair));
    System.out.println(map.getHashTable());

}
}//end of Mapping Class

这是输出

Size: 3

The content of the hash table

[table=table1, col=table1_age]  is mapped to [table=table1_SNT, col=table1_SNT_age]

[table=table1, col=table1_name] is mapped to [table=table1_SNT, col=table1_SNT_name]

[table=table1, col=table1_id]   is mapped to [table=table1_SNT, col=table1_SNT_id]

Testing the mapping

null

null

{[table=table1, col=table1_age]=[table=table1_SNT, col=table1_SNT_age], [table=table1, col=table1_name]=[table=table1_SNT, col=table1_SNT_name], [table=table1, col=table1_id]=[table=table1_SNT, col=table1_SNT_id]}

谢谢

最佳答案

我需要看看您对 Pair 的实现。我的猜测是您没有正确实现 equals 和 hashcode。

<小时/>

[编辑]

考虑到您对 Pair 的实现(摘自评论)

package preprocessingQuery; 
public class Pair { 
    private String table; 
    private String col; 
    public Pair(String table, String col) { 
        super(); 
        this.table = table; 
        this.col = col; 
    }

    public String getTable() { 
        return table; 
    }

    public void setTable(String table) { 
        this.table = table; 
    }

    public String getCol() { 
        return col; 
    }

    public void setCol(String col) { 
        this.col = col; 
    } 

    @Override public String toString() { 
        return "[table=" + table + ", col=" + col + "]"; 
    } 
}

您确实缺少 equals 和 hashcode。 一些背景:Object.equals 和 Object.hashCode 的默认实现是基于对象(对象引用)的内存地址。从这个角度来看,您的所有配对都是不同的,因为它们是不同的对象。

为了使任何集合实现正常工作,您需要覆盖要存储在集合中的对象的 equals 和 hashCode 的默认实现。

对于你的 Pair 类,它应该看起来像这样:

@Override
public boolean equals(Object other) {
    if (this == other) {
        return true; // shortcut for referential equality
    }
    if (other == null) {
        return false; // by definition, 'this' object is not null
    }
    if (!(other instanceof Pair)) {
        return false;
    }
    Pair otherPair  = (Pair) other; // Cast to the known type
    // check equality of the members
    if (this.table == null) {  
        if (otherPair.table != null) {
            return false;
        }
    } else if (!this.table.equals(otherPair.table)) {
        return false;
    }
    if (this.col == null) {  
        if (otherPair.col != null) {
            return false;
        }
    } else if (!this.col.equals(otherPair.col)) {
        return false;
    }
    return true;
}

HashCode 遵循套件。您应该理解并遵循the general contract of Hashcode

@Override
public int hashCode() {
    int hash = this.table==null?0:table.hashCode();
    hash += 41 * this.col==null?0:col.hashCode();
    return hash;
 }

关于java - 当我调用 hashTable.get(key) 时获取 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9158954/

相关文章:

java - 我如何将 JsonArray 从 jsp 解析为 Javascript

arrays - 数据结构的选择

c - 跟踪结果是否已经使用哈希表计算

parallel-processing - 键的替代哈希表相等性测试

c - 迭代时内核哈希表崩溃

java - 使用 XPath 和 XML XPath Api 获取 Soap Body

java - 机器人 JNI : app stops working

java - 如何将此水平 ViewPager 变压器修改为垂直变压器?

c# - 从哈希表中读取匹配的记录到类对象中

java - 无法使用 Guice 绑定(bind) TypeLiteral