繁体   English   中英

如何将2个数组从一个类传递到另一个类

[英]How do I pass 2 arrays from one class to another

我试图将我在这个类中创建的2个数组xArray []和yArray []传递给另一个类:

public class RungeCalculation {
    private double x;
    private double F1;
    private double F2;
    private double F3;
    private double F4;

    double[] xArray;
    double[] yArray;   

    public void solve(double y, double h, int j, double i) {      
        xArray = new double[j];
        yArray = new double[j];

        // code left out

        xArray[dex] = x;
        yArray[dex] = y;

        x = x + h;  
    }  

    private double f(double x, double y, double i){
         return i; 
    } 
}

如何将数组从RungeCalculation类传递到下面显示的RungeResult类并通过循环运行它们:(x和y是JTexArea)?

public class RungeResult extends JFrame {
    RungeResult() {
        // code left out

        for(int i = 0; i < xArray.length; i++) {
            x.append(" " + Double.toString(xArray[i]) + "\n");
        }
        for(int i = 0; i < yArray.length; i++) {
            y.append(" " + Double.toString(yArray[i]) + "\n");
        }
    }
}

我试图使函数调用数组,并使它们全局化,似乎都不起作用。

double[] xArr() {
    return xArray;
}
double[] yArr() {
    return yArray;
}

并在另一个类中调用它们:

double[] xArray = Arrays.xArr();
double[] yArray = Arrays.yArr();

哪个似乎没有成功。

你可以使用数组列表

list<Array[]> mylist = new list<Array[]>();
mylist.Add(xArray);
mylist.Add(yarray);

您应该声明xArr()yArr()方法是公共的,即:

public double[] xArr(){
    return xArr();
}

然后您可以通过以下方式使用它们:

RungeCalculation rungeCalculation = new RungeCalculation();
//calculate the arrays here somehow
double[] xArray = rungeCalculation.xArr();
double[] yArray = rungeCalculation.yArr();

您可以使用容器类来保存两个数组

如下

public class Pair<F, S> {
    public F first;
    public S second;

    /**
     * Constructor for a Pair.
     *
     * @param first the first object in the Pair
     * @param second the second object in the pair
     */
    public Pair(F first, S second) {
        this.first = first;
        this.second = second;
    }
}

用法:

class A{

   public Pair<int[], int[]> getTwoArrays() {
     //according your logic init xArray, yArray
     int[] xArray = new int[] {1, 2, 3, 4};
     int[] yArray = new int[] {1, 2, 3, 4};
     return new Pair(xArray, yArray);
   }

}


class B {


   public void useTwoArrays(Pair<int[], int[]> pairs) {
      int[] xArray = pairs.first;
      int[] yArray = pairs.second;
      // then do what you want to do

   }

}

关于Pair如果你在Android环境中点击这里 ,如果你在java环境中只是创建一个类如上面的Pairs,这是Java泛型 点击这里

暂无
暂无

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

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