【问题标题】:How to get a value from an array to be used in another class?如何从数组中获取要在另一个类中使用的值?
【发布时间】:2015-03-09 04:10:36
【问题描述】:

如果有数组如:

//....
int[] anArray;
anArray = new int[3];
anArray[0] = new otherClassWConst( x, y , z);
anArray[1] = new otherClassWConst( x, y , z);
anArray[2] = new otherClassWConst( x, y , z);
//....

x、y 和 z 的值都与数组中其他对象的其他 x、y 和 z 的值不同。 (这有意义吗?就像 anArray[0] 中 x 的值与 anArray[2] 中的值不同)。 注意:另一个类的构造函数需要这些参数,我不确定这是否重要

我如何在不同的类中获取每个数组值中的一个参数的值(例如,y 的值)。例如,有没有一种方法可以获得 Ys 的所有三个值,以便我可以将它们全部加到另一个类中?

例如

//code attaining only the y values of the array
overallValueOfY = Y + Y + Y; // or something of that nature
//life continues over here.

如果有什么不清楚的地方请告诉我,我已经尽力解释了。感谢您的考虑。

【问题讨论】:

  • 显示你的班级结构。

标签: java arrays class parameters constructor


【解决方案1】:

OtherClassConst 需要为其提供一个 get 方法:

public class OtherClassConst {
    private int x;
    private int y;
    private int x;

    public (int x, int y, int z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    public int getY() {
        return y;
    }
    /* Same concept for getX() and getZ() */
}

然后,你的类可以调用它:

int sumY = 0;
for (OtherClassConst c : myArray) {
    sumY += c.getY();
}

【讨论】:

  • 另外,您可以使用带有public final int 而不是private int 变量的不可变对象,并使用c.y 而不是c.getY()
【解决方案2】:

首先,除非您的新类扩展 Int,否则您的数组将无法工作,我只是想确保您知道这一点。

现在,你要做的就是在这个新类中创建一个 int 变量

int x;
int y;
int z;

并将它们设置为等于构造函数中的内容。然后创建一个返回值的新方法

public int getX(){
  return this.x;
}
public int getY(){
  return this.Y;
}
public int getZ(){
  return this.Z;
}

【讨论】:

  • 顺便说一句,如果 OP 不知道,你不能继承 int、任何原语,甚至是 Integer(这是最终的)。只要确保:-)
  • 子类化是什么意思?
  • @RythianLombard 这意味着扩展一个类。如果你想让一个类拥有另一个类的所有属性,你可以在开头写“extends someClass”。您的数组现在是为 int 制作的,但您正试图用其他类填充它,所以它不起作用。
【解决方案3】:

您需要使用 x、y 和 z 实例变量为您的其他类创建 POJO,然后使用 y 的 setter 方法获取值。遍历它们以获得值的总和。

【讨论】:

    【解决方案4】:

    如果您的其他 OtherClass 有一个返回整数的 getY 方法,那么您可以使用以下方法对它们求和:

    Arrays.stream(anArray).mapToInt(OtherClass::getY).sum();
    

    值得习惯使用流而不是 for 循环。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-07
      相关资源
      最近更新 更多