You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义Linked List报错:posX无法解析或不是字段

解决Processing自定义Linked List的posX cannot be resolved or is not a field错误

问题根源

  1. Node类泛型不完整:Node类的next字段未指定泛型,编译器将其视为原始类型,导致data被识别为Object,无法访问Garbage类的posX/posY字段。
  2. 笔误导致逻辑错误:主类中GarbageList.head = GarbageList.head.head;应为next而非head。
  3. 遍历删除逻辑漏洞:删除节点后直接移动指针,会跳过下一个节点的检查,可能漏删目标元素。

修复代码

1. 修正Node类(补全泛型)

class Node<T> {
  T data;
  Node<T> next; // 指定泛型类型,让编译器识别next的data类型

  Node(T data) {
    this.data = data;
    this.next = null;
  }
}

2. 修正removeGarbage函数

List<Garbage> GarbageList = new List<>();

void removeGarbage(int x,int y){
  // 处理头节点匹配的情况
  if(GarbageList.head != null && GarbageList.head.data.posX == x && GarbageList.head.data.posY == y){
    GarbageList.head = GarbageList.head.next; // 修正笔误,head改为next
    return; // 删除后直接返回,避免进入后续循环
  }

  // 处理非头节点的情况
  Node<Garbage> end = GarbageList.head;
  while (end != null && end.next != null) {
    if(end.next.data.posX == x && end.next.data.posY == y){
      end.next = end.next.next; // 删除目标节点
      // 删除后不移动指针,继续检查新的end.next
    } else {
      end = end.next; // 未删除时才移动指针
    }
  }
}

3. 优化List类(可选,消除原始类型警告)

class List<T> {
  Node<T> head;

  void add(T data) {
    Node<T> newNode = new Node<T>(data);
    if (head == null) {
      head = newNode;
    } else {
      Node<T> end = head; // 补全泛型,避免编译器警告
      while (end.next != null) {
        end = end.next;
      }
      end.next = newNode;
    }
  }
}

Garbage类保持不变

class Garbage{
  int type;
  int value;
  int posX, posY;
  PImage sprite;

  // 你的方法实现...
}

关键说明

  • 泛型补全后,编译器能正确推断data的类型为Garbage,解决posX无法解析的问题。
  • 删除头节点后直接返回,简化逻辑并避免不必要的循环。
  • 遍历过程中仅在未删除节点时移动指针,确保所有符合条件的节点都被检查到。

内容的提问来源于stack exchange,提问作者TeFurto777

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 12:45:03