Home > front end >  Store (x,y) coordinates in an ArrayList
Store (x,y) coordinates in an ArrayList

Time:12-16

I have a 2d array that looks like this:

1 1 1 1
1 1 1 1 
1 1 1 1
0 1 1 1

I want to store in an ArrayList called neighbors the right value of 0. However if I call

neigbors.add(location[4][1]) 

I will get the value "1", insted of (4,1). Is there any way I can do it? Let me mention I use these variables:

List<Integer> neighbors = new ArrayList<Integer>();
int[][] locations = new int[5][5];

CodePudding user response:

You should use a built in java class like Point.

List<Point> neighbors = new ArrayList<>();

Then when you add a point:

neighbors.add( new Point( 4, 1) );

You could use.

List<int[]> neighbors = new ArrayList<>();

then

neighbors.add( new int[]{ 4, 1} );

The reason you should use the java class, or create your own, is because it has meaningful hashCode and equals methods. Also, there is no guarantee that an int[] in your list has 2 elements.

CodePudding user response:

You can create a Point class that stores its x and y coordinate.

import java.util.Objects;
public class Point {
    private final int x, y;
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
    public int getX() {
        return x;
    }
    public int getY() {
        return y;
    }
    @Override
    public String toString() {
        return "Point [x="   x   ", y="   y   "]";
    }
    @Override
    public int hashCode() {
        return Objects.hash(x, y);
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Point other = (Point) obj;
        return x == other.x && y == other.y;
    }
}

Then you can create a List of Points.

List<Point> points = new ArrayList<>();
points.add(new Point(4, 1));
  • Related