我想将 4 个数组从 A 类中的方法传递给 B 类中的方法。 我在类 B 中的方法中创建了类 A 的实例来获取数组。
A类中的方法定义为Object[],我使用:
return new Object[]{Array1,Array2,Array3,Array4};
返回数组。
在 B 类的方法中,我得到的数组的对象定义为:
private Object outGeoObj[] = new Object[4];
我正在成功检索数组,但我想在再次使用该对象之前清除该对象。我尝试过:
public void ClearValues(){
if (outGeoObj != null){
outGeoObj = null;
}
else{
System.out.println("Object is null");
}
}
但它不起作用。有什么建议吗?
最小工作示例:
B类:
public class MainFem {
private OutGeoMesh outmesh;
private Object outGeoObj[] = new Object[4]; // [0: Xmpoint, 1: Ympoint, 2: Vec, 3: numpoints]
public MainFem() {
outmesh = new OutGeoMesh();
}
public void ClearValues(){
if (outGeoObj != null){
for(int i = 0; i < outGeoObj.length; i++) {
outGeoObj[i] = null;
}
}
else{
System.out.println("Object is null");
}
} // END Method ClearValues
public void MainStart(int Xpoint[][], int Ypoint[][], int nump[], int c2, int Line[][][], DrawPanel drawPanel){
outGeoObj = outmesh.createOutGeomesh(Xpoint, Ypoint, nump, c2, Line, drawPanel);
int temp = (int[][]) outGeoObj[3];
System.out.println(temp[0][0]);
}// End Method MainStart
} // END CLASS MainFem
A类:
public class OutGeoMesh {
private double Xmpoint[][][] = new double[500][200][20];
private double Ympoint[][][] = new double[500][200][20];
private double Vec[][][] = new double[500][2][20];
private int numpoints[][] = new int[500][20];
public OutGeoMesh() {
// TODO Auto-generated constructor stub
}
public Object[] createOutGeomesh(int Xpoint[][], int Ypoint[][], int nump[], int c2, int Line[][][], DrawPanel drawPanel) {
for (int j = 0; j <= c2; j++) {
for (int i = 0; i < nump[j]; i++) {
Vec[i][0][j] = i;
Vec[i][1][j] = i+1;
Xmpoint[i][0][j] = Xpoint[i][j];
Ympoint[i][1][j] = Ypoint[i][j];
numpoints[i][j] = numpoints[i][j] + 1;
} // END FOR i
} // END FOR j
return new Object[]{Xmpoint,Ympoint,Vec,numpoints};
} // END METHOD createOutGeomesh
// ---------------------------------
} // END CLASS OutGeoMesh
最佳答案
你需要做这样的事情:
Arrays.fill(outGeoObj, null);
您的代码不起作用的原因是您只是删除了对数组的引用,但代码的其他部分仍在使用同一数组。通过使用Arrays.fill
,您可以删除数组的内容。
关于java - Java中清晰的多维对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29462291/