简体   繁体   English

声明2d变量Java

[英]declare 2d variable Java

I am wondering whether it is possible to assign a value to a variable that would point to some exact position in the 2d Array in Java. 我想知道是否可以为一个变量赋值,该变量将指向Java中2d数组中的某个确切位置。 I am accessing array element through 我通过访问数组元素

imageMatrix[width][hight].getColor1()

and since I am considering different scenarios, it would be easier to declare [width][high] by eg. 由于我正在考虑不同的场景,因此通过例如声明[width] [high]会更容易。 n1=[2][1] and then call n1=[2][1]然后打电话

imageMatrix(n1).getColor1()

Is it somehow possible? 它有可能吗? Thanks! 谢谢!

You can define a class Coordinate that contains the width and height of a cell of your 2d array. 您可以定义一个包含二维数组单元格宽度和高度的坐标。 Then use an instance of this class to your imageMatrix() method. 然后使用此类的实例到imageMatrix()方法。

Something like: 就像是:

public clas Coordinate{
    private int height;
    private int width;
/*Accessors and constructors...*/


}

You can define ImageMatrix and Point as class. 您可以将ImageMatrix和Point定义为类。
For setting and getting color of each point you can create method inside Point class. 要设置和获取每个点的颜色,您可以在Point类中创建方法。
Here we are storing each point in a list so that we can access them in future. 在这里,我们将每个点存储在列表中,以便将来可以访问它们。

import java.util.ArrayList;
public class ImageMatrix {
    Point point;
    public ImageMatrix(Point point){
        this.point = point;
    }

    public static void main(String[] args) {
        //to set color and store each point into a list
        ArrayList<Point> pointList = new ArrayList<>();
        //creating 9 points with different color
        for(int i=0;i<3;i++){
            for(int j=0;j<3;j++){
                Point point = new Point(i,j);
                point.setColor("color"+i+j);
                pointList.add(point);
            }
        }
        //to get color from each point
        for(Point point : pointList){
            System.out.println("color of point " + point.height +" and " + point.width +" is : " + point.getColor());
        }
    }
}

class Point{
    public int height;
    public int width;
    public String color;

    public Point(int height, int width){
        this.height = height;
        this.width = width;
    }
    public void setColor(String color){
        this.color = color;
    }
    public String getColor(){
         return this.color;
    }
}

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

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