gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:25:33 25 4
gpt4 key购买 nike

我想问一个关于处理的问题。我有一个用户定义的对象类 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 的大小都不同。

如何才能实现上述目标?

最佳答案

使用二维数组怎么样?

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));
}
}
}
}

关于java - 声明处理中的可变大小动态对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18607711/

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