【问题标题】:Passing a Created Array Between Classes [Java]在类之间传递创建的数组 [Java]
【发布时间】:2018-01-05 20:25:11
【问题描述】:

我正在开发一个基本的图像处理程序,目前有 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    

}

如您所见,在创建图形时,会创建一个包含顶点对象的二维数组,然后为这些顶点对象分配具有共享颜色的适当邻居状态。我现在想在 Manipulations 中获取整个 aVertices 并对其进行处理,但我不确定如何在适当的范围内移动它。谁能指出我正确的方向?

【问题讨论】:

  • 请注意,您有两个名为 aVertices 的变量。我建议您了解两者之间的区别以及它们如何给您带来问题。 (注意一个是字段变量,另一个是局部变量。这两个术语可以帮助您找到更多信息。)
  • 如何创建每个类的对象?

标签: java class object scope


【解决方案1】:

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

对于你的问题,你可以在Graph中定义这样的方法。

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

Manipulations,你可以得到aVertices

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

【讨论】:

  • 是的,我对面向对象编程还是很陌生,谢谢你的上帝回答!我会尽可能接受。
  • 这是一个有用的tutorial
猜你喜欢
  • 2022-06-26
  • 2014-03-20
  • 2022-01-20
  • 2017-06-25
  • 1970-01-01
  • 1970-01-01
  • 2011-06-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多