【问题标题】:How to set an array as a parameter for a constructor?如何将数组设置为构造函数的参数?
【发布时间】:2022-01-15 12:28:32
【问题描述】:

我正在为我的班级做作业,这是我的代码。

public class Realty1 {
    Realty1 realty = new Realty1(incomeandCost[]);

    Realty1[] incomeAndCost = {
        new Realty1( 10000,  25000), new Realty1(35000,  100000), 
        new Realty1( 67000, 125000), new Realty1(89000,  199000), 
        new Realty1(105000, 250000), new Realty1(51000, 1025000)
    };
}

我只是很困惑,不确定如何实现这一点。我将数组添加为参数,因为没有它,代码将无法工作,但现在我收到“.class expected”错误。

【问题讨论】:

  • 对于参数的意图,数组只是一个普通的对象。例如,如果我们想编写一个方法foo,它以String-array 作为参数,我们可以这样写:void foo(String[] bar) { ... }
  • 假设你有public Realty1(Realty1[] a) { ... },那么你可以做Realty1 realty = new Realty1(incomeAndCost);(不需要括号,因为你传递了一个引用)假设有一个Realty1[]事先初始化(这意味着你必须交换两条线)。请注意,您是在类体内进行的,通常我们编写一个初始化/准备对象的方法。还要注意诸如incomeandCostRealty 之类的拼写错误
  • 你想在这里完成什么? Realty1 代表什么? Realty1 持有一组 Realty1 对象真的有意义吗?这种递归有时很有用,但在这种情况下似乎不是这样。

标签: java arrays


【解决方案1】:
public class Realty1 {
  int A;
  int B;
  Realty1 realty = new Realty1(incomeandCost[]);
  public Realty1(int A, int B){
     this.A = A;
     this.B = B;
  }
  Realty1[] incomeAndCost = {
     new Realty1( 10000,  25000), new Realty1(35000,  100000), 
     new Realty1( 67000, 125000), new Realty1(89000,  199000), 
     new Realty1(105000, 250000), new Realty1(51000, 1025000)
  };
}

【讨论】:

  • 这可能会导致无限循环和StackOverflowError - 创建Realty1 的实例时,会创建一个数组incomeAndCost填充 新实例Realty1... 此外,从 OP 的问题中复制的相同拼写错误,并且缺少接受数组的构造函数..
【解决方案2】:

看来这里实际上需要两个类:

  • 有两个整数字段,构造为Realty(int x, int y)
  • 带有Realty[]数组字段,构造为Realty1(Realty[] arr)

例子:

public class Realty {
    private int x, y;

    public Realty(int x, int y) {
        this.x = x;
        this.y = y;
    }
}
public class Realty1 {
    private Realty[] incomeAndCost;

    public Realty1(Realty[] incomeAndCost) {
        this.incomeAndCost = incomeAndCost; 
    }

    public Realty1() { // default no-args constructor
        this(new Realty[] {
            new Realty( 10_000,  25_000), new Realty(35_000,  100_000), 
            new Realty( 67_000, 125_000), new Realty(89_000,  199_000), 
            new Realty(105_000, 250_000), new Realty(51_000, 1025_000)
        });
    }
}

【讨论】:

  • 我同意你的评估,即 OP 试图做的事情可能需要两个不同的类。此外,Realty1 需要一个更有意义的名称。由于我们没有足够的信息,并不是说你应该在这里做,只是想为 OP 和未来的读者指出这一点。
  • @Code-Apprentice,两个类的分离是强制性的,因为在修正错别字之后,OP 会遇到StackOverflowError
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-27
  • 1970-01-01
  • 1970-01-01
  • 2010-12-29
  • 1970-01-01
  • 2021-07-18
相关资源
最近更新 更多