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

出现ArrayList<PVector>转PVector错误:如何实现嵌套ArrayList?

问题解决:嵌套ArrayList类型不匹配及逻辑修正

错误原因分析

  1. 类型不匹配:sphereList是ArrayList<ArrayList<PVector>>,调用get(i)返回的是ArrayList<PVector>类型,但你试图把它赋值给PVector类型的变量v3,这就触发了Cannot convert from ArrayList<PVector> to PVector错误。
  2. 逻辑错误:在pointSphere方法中,你反复将同一个sphere1列表添加到sphereList里,最终sphereList里的所有元素都会指向同一个ArrayList<PVector>实例,这不符合你存储多个独立点集的需求。

修正步骤

  1. 修复遍历嵌套列表的代码:遍历sphereList时,先取出内层的ArrayList<PVector>,再遍历这个内层列表获取PVector。
  2. 修正pointSphere方法的逻辑:每次外层循环(u循环)创建一个新的ArrayList<PVector>,把当前纬度圈的点添加到这个新列表中,再将新列表加入sphereList,避免重复添加同一个列表实例。

修正后的完整代码

//position variable for pointSphere
float x;
float y;
float z;

// 嵌套ArrayList的正确声明:存储ArrayList<PVector>的列表
ArrayList<ArrayList<PVector>> sphereList = new ArrayList<ArrayList<PVector>>();

void setup() {
  size(1920, 1080, P3D);
  pointSphere(270, 27, 27);
}

void draw() {
  background(0);

  pushMatrix();
  translate(500, 500, 100);
  
  // 遍历sphereList中的每个内层列表
  for (int i = 0; i < sphereList.size(); i++) {
    ArrayList<PVector> currentSphere = sphereList.get(i);
    // 遍历内层列表中的每个PVector
    for (PVector v3 : currentSphere) {
      stroke(255);
      strokeWeight(random(2, 10));
      point(v3.x, v3.y, v3.z);
    }
  }
  
  popMatrix();
}

void pointSphere (float r, float uAmount, float wAmount) {
  for (float u= 0; u < 180; u += 180/uAmount) {
    // 每次u循环创建新的ArrayList,存储当前纬度的所有点
    ArrayList<PVector> currentSphere = new ArrayList<PVector>();
    for (float w = 0; w < 360; w += 360/wAmount) {
      // 生成当前点的PVector
      PVector vS1 = new PVector(
        r*sin(radians(u))*cos(radians(w)), 
        r*sin(radians(u))*sin(radians(w)), 
        r*cos(radians(u))
      );
      currentSphere.add(vS1);
    }
    // 将当前纬度的点列表加入sphereList
    sphereList.add(currentSphere);
  }
}

额外说明

  • 嵌套泛型的正确语法是ArrayList<ArrayList<PVector>>,你一开始的声明是对的,后面注释掉的几种写法都是错误的泛型嵌套方式,不需要尝试。
  • 遍历嵌套列表时,必须先获取内层容器,再遍历容器中的元素,不能直接跳过内层容器去拿元素。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 15:25:32