在处理中声明可变大小的动态对象数组

时间:2013-09-04 07:19:48

标签: java processing

我想问一个关于Processing的问题。我有一个用户定义的对象类Point,它有两个数据成员x和y都声明为float。我有另一个类识别器。我需要创建Recognizer的构造函数,并在其中定义动态的Point[] point0, Point[] point1等对象...

Point [] point0={new Point(137,139),new Point(50,63),..., new Point(78,5)};
so is point1[],point2[],...,pointn[]

如何将值添加到具有相应x和y坐标值的point0中。

另请注意,每个对象point1,point2,..., pointn的大小不同。

我如何实现上述目标?

1 个答案:

答案 0 :(得分:1)

使用二维数组怎么样?

Point [] points0={new Point(137,139),new Point(50,63),new Point(78,5)};
Point [] points1={new Point(147,139),new Point(60,63),new Point(79,5)};
Point [] points2={new Point(157,139),new Point(70,63),new Point(80,5)};

void setup(){
  Point[][] pointLists = {points0,points1,points2};
  Recognizer r = new Recognizer(pointLists);
}

class Point{
  float x,y;
  Point(float x,float y){
    this.x = x;
    this.y = y;
  }
  String toString(){
    return "Point("+x+","+y+")";
  }
}
class Recognizer{
  Point[][] data;
  Recognizer(Point[][] data){
    this.data = data;
    for(int i = 0 ; i < data.length; i++){
      println("processing points list" + i);
      for(int j = 0; j < data[i].length; j++){
        println("processing point["+j+"] of list " + i + " : "+data[i][j]);
      }
    }
  }
}

和ArrayList版本:

import java.util.Arrays;

ArrayList<Point> points0 = new ArrayList<Point>(Arrays.asList(new Point[]{new Point(137,139),new Point(50,63),new Point(78,5)}));
ArrayList<Point> points1 = new ArrayList<Point>(Arrays.asList(new Point[]{new Point(147,139),new Point(60,63),new Point(79,5)}));
ArrayList<Point> points2 = new ArrayList<Point>(Arrays.asList(new Point[]{new Point(157,139),new Point(70,63),new Point(80,5)}));

void setup(){
  ArrayList<ArrayList<Point>> pointLists = new ArrayList<ArrayList<Point>>();
  pointLists.add(points0);
  pointLists.add(points1);
  pointLists.add(points2);
  Recognizer r = new Recognizer(pointLists);
}

class Point{
  float x,y;
  Point(float x,float y){
    this.x = x;
    this.y = y;
  }
  String toString(){
    return "Point("+x+","+y+")";
  }
}
class Recognizer{
  ArrayList<ArrayList<Point>> data;
  Recognizer(ArrayList<ArrayList<Point>> data){
    this.data = data;
    for(int i = 0 ; i < data.size(); i++){
      println("processing points list" + i);
      for(int j = 0; j < data.get(i).size(); j++){//write this in a nicer way, too many get calls, might want a reusable variable here
        println("processing point["+j+"] of list " + i + " : "+data.get(i).get(j));
      }
    }
  }
}