简体   繁体   English

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

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

I am trying to create an ArrayList with the dimensions of certain shapes. 我正在尝试创建具有某些形状尺寸的ArrayList My code is: 我的代码是:

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

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

I am aware this is doesn't work but how would I add a pair such as (2.5,3.5) to an array? 我知道这不起作用,但我如何将一对如(2.5,3.5)到数组中?

Make your own class: 创建自己的课程:

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

Then make an ArrayList of that type: 然后创建该类型的ArrayList

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

Adding to it: 添加到它:

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

If you want to get the x or the y coordinate, you can simply have additional methods in your class, for example public double getX() { return x; } 如果要获取xy坐标,可以在类中添加其他方法,例如public double getX() { return x; } public double getX() { return x; } and then you can do: public double getX() { return x; }然后你可以这样做:

shapes.get(0).getX();

* This is only an example, modify the code as you see it fits your needs *这只是一个示例,修改代码,因为您认为它符合您的需求

This might be you are looking for 这可能是你正在寻找的

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

Still , prefer to use Maroun's Suggestion. 不过,更喜欢使用Maroun的建议。 That Looks clean to me, because later you may want to add more properties to that Shape object. 这看起来很干净,因为以后您可能想要为该Shape对象添加更多属性。

Create a model class such as : 创建一个模型类,例如:

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

Now you can add in arraylist by the following way: 现在,您可以通过以下方式添加arraylist:

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

And access it by the following way: 并通过以下方式访问它:

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

I know this is old but I had to do something like this recently, store your co-ordinates as an array as such : 我知道这是旧的,但我最近必须做这样的事情,将你的坐标存储为数组:

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

That should do it. 应该这样做。

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

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