英文:
Generic Array Creating When I'm Not Using Generics
问题
在尝试在Java中实现斐波那契堆(Fibonacci Heap)时,即使我没有使用泛型,也出现了通用数组创建错误。
private void consolidate() {
Node[] degrees = new Node[45];
}
Node
类如下:
private class Node {
public E val;
public Node left, right, child;
public int degree;
public boolean mark;
public Node(E _val) {
val = _val;
}
public void insert(Node newNode) {
if(left == this) {
left = newNode;
right = newNode;
left.right = this;
left.left = this;
} else {
Node temp = left;
left = newNode;
left.right = this;
left.left = temp;
temp.right = left;
}
}
public void unlink() {
left.right = right;
right.left = left;
if(child != null) {
Node dummy = child;
do {
left.insert(dummy);
dummy = dummy.left;
} while(dummy != child);
}
}
}
我认为可能是以下部分导致了错误:
public E val;
以及
public Node(E _val) {
val = _val;
}
但是,我将它们都更改为 Object
,但仍然无法工作。如果有帮助的话,E
是继承了 Comparable<E>
的:
public class FibonacciHeap<E extends Comparable<E>>
英文:
When trying to implement Fibonacci Heap in Java I'm getting a generic array creation error even though I'm not using generics.
private void consolidate() {
Node[] degrees = new Node[45];
}
The Node
class is this:
private class Node {
public E val;
public Node left, right, child;
public int degree;
public boolean mark;
public Node(E _val) {
val = _val;
}
public void insert(Node newNode) {
if(left == this) {
left = newNode;
right = newNode;
left.right = this;
left.left = this;
} else {
Node temp = left;
left = newNode;
left.right = this;
left.left = temp;
temp.right = left;
}
}
public void unlink() {
left.right = right;
right.left = left;
if(child != null) {
Node dummy = child;
do {
left.insert(dummy);
dummy = dummy.left;
} while(dummy != child);
}
}
}
I thought that maybe this part was causing the error:
public E val;
and
public Node(E _val) {
val = _val;
}
however I changed both of them to Object
, and it still didn't work. If it helps, E
extends Comparable<E>
.
public class FibonacciHeap<E extends Comparable<E>>
答案1
得分: 1
你的类FibonacciHeap
实际上是泛型的,所以它内部的私有类Node
也是泛型的,正如在第一个注释中提到的那样。
如果你认为Node
类不应该是泛型的,你可以通过使用Object val
将其变为内部静态类:
public class FibonacciHeap<E extends Comparable<E>> {
private static class Node {
Object val;
// ...
}
}
或者将其定义移出FibonacciHeap
:
public class FibonacciHeap<E extends Comparable<E>> {
}
private class Node {
Object val;
// ...
}
还有一种选择是从FibonacciHeap
中移除泛型。
英文:
Your class FibonacciHeap
is generic actually, so its inner private class Node
is generic too as mentioned in the first comment.
If you think your Node class should not be generic, you can either make it inner static class using Object val
:
public class FibonacciHeap<E extends Comparable<E>> {
private static class Node {
Object val;
// ...
}
}
or move its definition outside FibonacciHeap
:
public class FibonacciHeap<E extends Comparable<E>> {
}
private class Node {
Object val;
// ...
}
There's also an option to remove generic from FibonacciHeap
too.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论