gpt4 book ai didi

java - 奇怪的 Java 编译器错误 (Error :(65, 23) java : incompatible types: Bag. Node 无法转换为 Bag.Node )

转载 作者:行者123 更新时间:2023-11-30 07:47:40 28 4
gpt4 key购买 nike

我很困惑。我无法将外部类的实例变量 Node first 分配给内部类的实例变量 Node current 。编译器提示存在不兼容的类型。如果我应用 Actor ,它会起作用。这里发生了什么。

import java.util.*;
import java.lang.Iterable;

class Bag<Item> implements Iterable<Item> {

private class Node<Item> {
private Item item;
private Node<Item> next;
}

private Node<Item> first;
private int size;

public Bag() {
first = null;
size = 0;
}

public void add(Item item) {
Node<Item> oldNode = first;
Node<Item> newNode = new Node<>();
newNode.item = item;
newNode.next = oldNode;
first = newNode;
size++;
}

public boolean isEmpty() { return first == null; }
public int getSize() { return size; }

public Iterator<Item> iterator() {
return new ListIterator<Item>(first);
}

private class ListIterator<Item> implements Iterator<Item> {
private Node<Item> current;

public ListIterator(Node<Item> node) {
// Error is here Error:(65, 23) java: incompatible types: Bag<Item>.Node<Item>
//cannot be converted to Bag<Item>.Node<Item>
// current and first are of the same type (Node<Item>).
// What is the problem, why shall I apply when the types are the same.
current = first;
}

@Override
public boolean hasNext() {
return current != null;
}

@Override
public void remove() {
throw new UnsupportedOperationException("remove");
}

@Override
public Item next() {
if (!hasNext()) throw new NoSuchElementException();
Item item = current.item;
current = current.next;
return item;
}
}

public String toString() {
StringBuilder s = new StringBuilder();
Iterator<Item> it = iterator();
while (it.hasNext())
s.append(it.next() + " ");

return s.toString();
}
}

public class Main {

public static void main(String[] args) {
int data[] = new int[5];
Bag<Integer> bag = new Bag<>();

for (int i = 0; i < data.length; i++)
data[i] = new Random().nextInt(1000);

//Arrays.sort(data);
System.out.println(Arrays.toString(data));

for (int i = 0; i < data.length; i++)
bag.add(data[i]);

System.out.println( "Size: " + bag.getSize() );
System.out.println( bag );

}
}

最佳答案

改变

private class Node<Item> {

private class ListIterator<Item> implements Iterator<Item> {

private class Node {

private class ListIterator implements Iterator<Item> {

关于java - 奇怪的 Java 编译器错误 (Error :(65, 23) java : incompatible types: Bag<Item>. Node<Item> 无法转换为 Bag<Item>.Node<Item> ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33699508/

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