簡體   English   中英

當我調用hashTable.get(key)時得到null

[英]Getting null when I call hashTable.get(key)

我的項目中有Pair類,並且在應用程序中使用哈希表。 構造哈希表之后,我將通過打印哈希的內容來測試是否創建了Pair對象並將其正確存儲在哈希表中,然后立即嘗試使用get(key)方法獲取值之一,並且它始終給出我沒有。

這是我的整個類Mapping,它具有一個類型為hashtable package metastore的私有對象。

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]}

謝謝

我需要查看您對的實現。 我的猜測是您沒有正確實現equals和hashcode。


[編輯]

考慮到您對的實現(摘自評論)

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遵循套件。 您應該了解並遵守Hashcode的一般合同

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

這是由於您沒有覆蓋類Pair中的equals和hashCode方法,或者至少沒有正確地覆蓋它們。 當您在哈希表上調用“ get”時,哈希表將首先調用hashCode方法以在其表中查找條目。 如果未正確覆蓋hashCode,則哈希表將找不到您的條目。 其次,當hashtable找到該條目時,它將測試該條目的鍵是否等於您提供的鍵(在hashCode沖突的情況下)。 您可以像這樣覆蓋這些方法:

public int hashCode {
   return table.hashCode()+tableName.hashCode();
}

public boolean equals(Object o) {
   if (o==this)
       return true;
   if (o instanceof Pair) {
       Pair p = (Pair) o;
       return this.table.equals(p.table) && this.tableName.equals(p.tableName);
   }
   return false;
}

最后,當您遍歷Hashtable(通常是通過Map)時,不應調用鍵並執行get(key),而應直接對Entries進行迭代。

for(Entry<K,V> e: map.entrySet()) {
   System.err.println(e.getKey+" is mapped to "+e.getValue());
}

它效率更高,因為它不會調用hashCode和equals方法(如上所述),這可能是昂貴的操作。

重新定義類Pair中的equalshashcode

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM