HashMap对象数组数据被替换

时间:2015-05-19 06:54:39

标签: java object hashmap

我将数据添加到HashMap中,其中node是一个具有变量索引和后继的对象。

private static HashMap <Integer, node> peerList = new HashMap<Integer, node>();

public void generateFingerTable (int node_position) {

            chordSize = chord.initChordSize;        
            chord chord = new chord();  

        //create new node and add to map
        node newPeer = new node();
        peerList.put(node_position, newPeer);

        for (int i=0; i<chordSize; i++) {

            int temp = i+1;

            newPeer.index = new int [chordSize];
            newPeer.successor = new int [chordSize];

            int temp1 = node_position + (int)Math.pow(2, temp-1) % chord.getChordSize();

            peerList.get(node_position).index[i] = temp;                
            peerList.get(node_position).successor[i] = temp1;

            System.out.println ("Index: "  + newPeer.index[i] + "\n" + "Successor: " + 
                    newPeer.successor[i]);          
        }
}

public void printFingerTable() {

        for (Map.Entry<Integer, node> m : peerList.entrySet()) {
            System.out.println ("Peer " + m.getKey() + " with Index: " + m.getValue().getIndex() + " Successor: " +
                                    m.getValue().getSuccessor());
        }

当我打印Hash细节时,结果显示Index:[0,0,0,0,5],Successor:[0,0,0,0,16]表示先前添加的元素被替换,仅最后一个元素保存在Hashmap中。

预期结果应为索引[1,2,3,4,5],后继者:[1,2,4,8,16]。 我该如何修改这些数据,以免数据被替换?

2 个答案:

答案 0 :(得分:1)

您在循环的每次迭代中初始化indexsuccessor数组,因此只有最后一个索引的值保留在最后,其他索引为0。

您应该在循环之前初始化数组。

将代码更改为:

public void generateFingerTable (int node_position) {

        chordSize = chord.initChordSize;        
        chord chord = new chord();  

        //create new node and add to map
        node newPeer = new node();
        peerList.put(node_position, newPeer);

        newPeer.index = new int [chordSize];
        newPeer.successor = new int [chordSize];
        for (int i=0; i<chordSize; i++) {
            int temp = i+1; 
            int temp1 = node_position + (int)Math.pow(2, temp-1) % chord.getChordSize();
            peerList.get(node_position).index[i] = temp;                
            peerList.get(node_position).successor[i] = temp1;

            System.out.println ("Index: "  + newPeer.index[i] + "\n" + "Successor: " + 
                    newPeer.successor[i]);          
        }
}

答案 1 :(得分:0)

我认为你应该使用与HashMap不同的数据类型或结构,因为HashMaps不保证顺序。我指出这一点,因为你的代码Select * from subject order by CASE WHEN Subject.Title = 'English' THEN '1' WHEN Subject.Title = 'Urdu' THEN '2' WHEN Subject.Title = 'Mathematics' THEN '3' WHEN Subject.Title = 'Science' THEN '4' 似乎暗示你在HashMap中设置对象的位置但事实并非如此。我之所以这么说,是因为您只是使用名为peerList.put(node_position, newPeer);的变量来键入或散列您的数据对象将存在于HashMap中的位置。有关详细信息,请参阅此链接。

Difference between HashMap, LinkedHashMap and TreeMap

相关问题