在类之间传递创建的数组[Java]

时间:2017-07-30 03:09:24

标签: java class object scope

我正在研究一个基本的图像处理程序,目前有3个类:Vertex,Graph和Manipulations。

public class Vertex{
    //Vertex functions, including tracking neighbours
}

public class Graph{

    Vertex[][] aVertices;

    public Graph(Color[][] image){

        int xTop = 0;
        for (int i = 0; i < image.length; i++){
            if (i > xTop){
                xTop = i;
            }
        }    

        int yTop = image.length;

        Vertex[][] aVertices = new Vertex[xTop][yTop];

        for(int i = 0; i < xTop; i++){
            for(int j = 0; j < yTop; j++){
                Vertex newVertex = new Vertex(i, j, image[i][j]);
                aVertices[i][j] = newVertex;
            }
        }    

        for(int i = 0; i < xTop; i++){
            for(int j = 0; j < yTop; j++){
                if(aVertices[i][j] == aVertices[i-1][j]){
                    aVertices[i][j].neighbourize(aVertices[i-1][j]);
                }
                if(aVertices[i][j] == aVertices[i+1][j]){
                    aVertices[i][j].neighbourize(aVertices[i+1][j]);
                }
                if(aVertices[i][j] == aVertices[i][j-1]){
                    aVertices[i][j].neighbourize(aVertices[i][j-1]);    
                }
                if(aVertices[i][j] == aVertices[i][j+1]){
                    aVertices[i][j].neighbourize(aVertices[i][j+1]);
                }
            }
        }

    }

}

public class Manipulations{

    //Image manipulations that access aVertices    

}

如您所见,在创建图形时,会创建一个包含顶点对象的2D数组,然后为顶点对象分配适当的邻居状态和共享颜色。我现在想要整个aVertices并在Manipulations内部工作,但我不确定如何在适当的范围内移动它。有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:1)

我认为你缺乏Object Oriented Programming的知识。

对于您的问题,您可以在Graph中定义此类方法。

public Vertex[][] getVertices() {
  return this.aVertices;
}

Manipulations中,您可以使用

获取aVertices
Graph g = new Graph(image);
Vertex[][] vertices = g.getVertices();