gpt4 book ai didi

java - 当每个实例传递唯一值时,自定义 "Node"类的两个实例都会打印相同的值

转载 作者:行者123 更新时间:2023-12-02 03:15:48 24 4
gpt4 key购买 nike

我正在尝试基于 Entry 对象创建一个新节点。我检索 2 个不同的条目并打印出它们的键和值。打印出来的两个 key 是不同的。我将每个键和值存储到单独的“节点”n1 和 n2 中。 Node 是我创建的自定义类,其代码可以在下面找到。当我打印出 n1 的键和 n2 的键的值时,它们应该是不同的,因为条目的键是,但由于某种原因它打印出相同的值。我不知道为什么会发生这种情况,我也想不通。这是我目前的代码:

节点类:

import java.util.HashMap;
import java.util.Map.Entry;

public class Node {
public static Entry<String, Integer> keyVal;
public static Node leftChild;
public static Node rightChild;
public static String bitCode;

public Node() {
keyVal = null;
leftChild = null;
rightChild = null;
}

public Node(Entry<String, Integer> entry) {
keyVal = entry;
leftChild = null;
rightChild = null;
}

public Node(Entry<String, Integer> entry, Node n1, Node n2) {
keyVal = entry;
leftChild = n1;
rightChild = n2;
}

public Entry<String, Integer> getEntry() { return keyVal; }

public Node getLeftChild() { return leftChild; }

public Node getRightChild() { return rightChild; }

public void setLeftChild(Node lc) {
leftChild = lc;
}

public void setRightChild(Node rc) {
leftChild = rc;
}
}

主类中的createTree方法:

private static Node createTree(PriorityQueue<Entry<String, Integer>> pq) {
map = new HashMap<>(); // Defined as a public attribute to the Main class
Entry<String, Integer> entry1 = null;
Entry<String, Integer> entry2 = null;
Entry<String, Integer> parent = null;
Node n1 = null;
Node n2 = null;
Node n3 = null;
System.out.println("PQ size: " + pq.size());

while (pq.size() > 1) {
entry1 = pq.poll();
// Prints "Entry1: R 1"
System.out.println("Entry1: " + entry1.getKey() + " " + entry1.getValue());

entry2 = pq.poll();
// Prints "Entry2: e 1"
System.out.println("Entry2: " + entry2.getKey() + " " + entry2.getValue());

// Never enters if, goes to else
if (map.containsKey(entry1.getKey())) {
System.out.println("Map contains entry1!");
n1 = map.get(entry1.getKey());
} else {
n1 = new Node(entry1);
}
// Never enters if, goes to else
if (map.containsKey(entry2.getKey())) {
System.out.println("Map contains entry2!");
n2 = map.get(entry2.getKey());
} else {
n2 = new Node(entry2);
}
// Should print "N1: R 1", Instead prints "N1: e 1"
System.out.println("N1: " + n1.getEntry().getKey() + " " + n1.getEntry().getValue());
// Prints "N2: R 1"
System.out.println("N2: " + n2.getEntry().getKey() + " " + n2.getEntry().getValue());
}

最佳答案

发生这种情况是因为类 Node 中的成员是静态的:

//From the 'Node' class:
public static Entry<String, Integer> keyVal;
public static Node leftChild;
public static Node rightChild;
public static String bitCode;
//...

因此,当您创建第二个 Node 时,执行以下操作:

 n1 = new Node(entry1);

您覆盖首先输入的值:

n2 = new Node(entry2);

关于java - 当每个实例传递唯一值时,自定义 "Node"类的两个实例都会打印相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40333840/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com