简体   繁体   中英

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

I am trying to create an ArrayList with the dimensions of certain shapes. 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?

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<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; } public double getX() { return x; } and then you can do:

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. That Looks clean to me, because later you may want to add more properties to that Shape object.

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<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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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