简体   繁体   English

将 object 添加到单独的 class 中的数组

[英]Adding an object to an array in a separate class

edit: I am looking to pass HomeBuyers Objects to my homeBuyers ArrayList in my CreditUnion class. The this.homeBuyers.add function throws a "cannot find symbol" error.编辑:我希望将 HomeBuyers 对象传递给我的 CreditUnion class 中的 homeBuyers ArrayList。this.homeBuyers.add function 抛出“找不到符号”错误。 I have tried making the firstName, lastName, and creditScore vars static and passing the object in with HomeBuyers(HomeBuyers.firstName, HomeBuyers.lastName, HomeBuyers.creditScore).我已经尝试制作 firstName、lastName 和 creditScore 变量 static 并将 object 传递给 HomeBuyers(HomeBuyers.firstName, HomeBuyers.lastName, HomeBuyers.creditScore)。 That avoided errors but did not add the object to the ArrayList.这避免了错误,但没有将 object 添加到 ArrayList。

public class LabProgram {

public static void main(String[] args) {

    CreditUnion cu = new CreditUnion();

    cu.addHomeBuyer(new HomeBuyers("first","last",600));

    }

}

  public class HomeBuyers {
    public String firstName;
    public String lastName;
    public int creditScore;

public HomeBuyers(String firstName, String lastName, int creditScore) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.creditScore = creditScore;
  }

  }

   public class CreditUnion {
     public ArrayList<HomeBuyers> homeBuyers;

public CreditUnion() {
    this.homeBuyers = new ArrayList<>();
      }


public void addHomeBuyer(HomeBuyers homeBuyers) {
     this.homeBuyers.add(HomeBuyers(firstName, lastName, creditScore));
}

You have multiple problems here.你在这里有多个问题。

The right syntax for creating a new object is new HomeBuyers(...) .创建新的 object 的正确语法是new HomeBuyers(...) Not HomeBuyers() .不是HomeBuyers()

Separately, firstName doesn't exist as a variable in your addHomeBuyer method.另外, firstName在您的addHomeBuyer方法中不作为变量存在。 The only variable that does exist is homeBuyers .唯一存在的变量是homeBuyers You could write homeBuyers.firstName .你可以写homeBuyers.firstName However, you already have an instance of your class HomeBuyers .但是,您已经拥有class HomeBuyers的实例。 There is no need to make another one with identical values.没有必要制作另一个具有相同值的。 this.homeBuyers.add(homeBuyers) would have done the job. this.homeBuyers.add(homeBuyers)就可以完成这项工作。

These questions are incredibly simplistic;这些问题非常简单; stack overflow probably isn't the right venue.堆栈溢出可能不是正确的地点。 I suggest any of the many nice tutorials out there, they tend to take a little more time to explain things in an orderly fashion.我推荐许多不错的教程中的任何一个,它们往往会花更多的时间以有序的方式解释事情。

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

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