1

我想问一个关于处理的问题。我有一个用户定义的对象类 Point,它有两个数据成员 x 和 y 都声明为浮点数。我有另一个类识别器。我需要创建识别器的构造函数,并在其中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是不同的。

我怎样才能实现上述目标?

4

1 回答 1

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));
      }
    }
  }
}
于 2013-09-04T08:00:51.570 回答