【问题标题】:Adding an instance of a class in to an array list in a different class, automatically upon creation of the instance在创建实例时自动将类的实例添加到不同类的数组列表中
【发布时间】:2014-10-30 12:41:21
【问题描述】:

对编程相当陌生,所以不确定我所问的是否真的可行。

我有一个类,Man,它只包含类的参数,还有一些 get 方法来查找对象的特定参数。

我有另一个班级Group,我想在其中有一个ArrayListMan

顺便说一句,我正在学习使用 bluej 环境,如果这会有所不同的话。

这是Man 类的相关部分。

import java.util.ArrayList;
/**
*This class will store information about man, including the height, weight, age and year of birth
*of individual men.
*/
public class Man
{
// stats.
public int Height;
public int Weight;
public int Age;
public int Year;


/**
 * The user will input the stats about the man in input parameters.
 */
public Man(int Height, int Weight, int Age, int Year)
{
    this.Height = Height;
    this.Weight = Weight;
    this.Age = Age;
    this.Year = Year;
  }

下面有一些获取统计信息的方法。

在我的另一个类Group 中,我希望上述类的所有实例都进入ArrayList。 到目前为止,我有:

import java.util.ArrayList;
/**
*Record all men.
*/
public class Group
{

public ArrayList <Man> AllMen;

/**
 * Constructor for objects of class Group
 */
public Group()
{
    AllMen = new ArrayList <Man>();
}

public void AddMan(int Height, int Weight, int Age, int Year) {
    AllMen.add(new Man(Height, Weight, Age, Year,)); //trying to get it to list all men created.
}

}

他们两个似乎并没有像我想象的那样联系在一起。我错过了什么?

【问题讨论】:

  • 而确切的问题是?你期待什么,你得到了什么?
  • 我期待(或希望)当我创建一个 man 对象时,它会自动移动到 AllMen 数组列表,但它无法识别 Group 类中的 Man。
  • 好吧,您的AddMan 方法似乎做得很好。我不是 Java 开发人员,但如果 Group 没有看到 Man,那可能是因为这两个类不在同一个包中。

标签: java arrays class arraylist dependencies


【解决方案1】:

如果我没记错的话,你必须在你的 Group 类中创建你的 Man 类的对象,而不是使用它的所有实例变量和方法

【讨论】:

  • 感谢您的帮助。我试过了,程序似乎没有问题,但现在 Man 类没有出现在我的对象台上,这意味着我无法运行其中的方法。你知道我如何访问它们吗?谢谢。
猜你喜欢
  • 1970-01-01
  • 2013-12-02
  • 1970-01-01
  • 2022-01-20
  • 2015-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多