javaarraylist

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?


Solution

  • 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; } and then you can do:

    shapes.get(0).getX();
    

    * This is only an example, modify the code as you see it fits your needs