繁体   English   中英

如何在ArrayList中添加一对数字?

[英]How can I add a pair of numbers to an ArrayList?

我正在尝试创建具有某些形状尺寸的ArrayList 我的代码是:

ArrayList<Double> shapes = new ArrayList<Double>();

shapes.add(2.5,3.5); 
shapes.add(5.6,6.5);
shapes.add(8.4,6.9);

我知道这不起作用,但我如何将一对如(2.5,3.5)到数组中?

创建自己的课程:

public class MyClass {
   double x;
   double y;
   public MyClass(double x, double y) {
      this.x = x;
      this.y = y;
   }
}

然后创建该类型的ArrayList

ArrayList<MyClass> shapes = new ArrayList<>();

添加到它:

MyClass pair = new MyClass(2.5,3.5);
shapes.add(pair);

如果要获取xy坐标,可以在类中添加其他方法,例如public double getX() { return x; } public double getX() { return x; }然后你可以这样做:

shapes.get(0).getX();

*这只是一个示例,修改代码,因为您认为它符合您的需求

这可能是你正在寻找的

List<double []> shapes = new ArrayList<>();
shapes.add(new double [] {2.5,3.5});

不过,更喜欢使用Maroun的建议。 这看起来很干净,因为以后您可能想要为该Shape对象添加更多属性。

创建一个模型类,例如:

public class Dimensions{
   private double l;
   private double b;
  public Dimensions(double l, double b){
    this.l=l;
    this.b=b;
  }
  public void setL(double l){
   this.l=l;
  }
  public void setB(double b){
   this.b=b;
  }
  public double getB(){
   return this.b;
  }
  public double getL(){
   return this.l;
  }
}

现在,您可以通过以下方式添加arraylist:

ArrayList<Dimensions> shapes=new ArrayList<Dimensions>();
shapes.add(new Dimensions(2.5,3.5));
shapes.add(new Dimensions(5.6,6.5));

并通过以下方式访问它:

double l;
double b;
for(Dimensions dimensions:shapes){
 l=dimensions.getL();
 b=dimensions.getB();
 //some more dimensions specific code goes here
}

我知道这是旧的,但我最近必须做这样的事情,将你的坐标存储为数组:

class yourclass{
ArrayList<yourclass> arr[];
void addcord(double x,double y)  {
arr[(int)x].get((int) y);
}
}

应该这样做。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM