java - 如何将方法调用到对象数组中?

标签 java arrays object methods call

我有两个类。一个名为 Cat 的类,包含猫的名字、出生年份和体重(以公斤为单位)。我有一个名为 Cattery 的类,它是一个数组。我想将 Cat 类中的猫输入到数组中。每只猫都有自己的名字、出生年份和体重(公斤)。我该怎么做呢?谢谢。

public class Cat {

    private String name;
    private int birthYear;
    private double weightInKilos;

/**
 * default constructor
 */ 
public Cat() {   
}

/**
 * @param name
 * @param birthYear
 * @param weightInKilos
 */
public Cat(String name, int birthYear, double weightInKilos){   
    this.name = name;
    this.birthYear = birthYear;
    this.weightInKilos = weightInKilo
}

/**
 * @return the name.
 */
public String getName() {
    return name;
}

/**
 * @return the birthYear.
 */
public int getBirthYear() {
    return birthYear;
}

/**
 * @return the weightInKilos.
 */  
public double getWeightInKilos() {
    return weightInKilos;
}

/**
 * @param the name variable.
 */
public void setName(String newName) {
    name = newName; 
}

/**
 * @param the birthYear variable.
 */
public void setBirthYear(int newBirthYear) {
    birthYear = newBirthYear;
}

/**
 * @param the weightInKilos variable.
 */
public void setWeightInKilos(double newWeightInKilos) {
    weightInKilos = newWeightInKilos;
} 
}

数组类。

import java.util.ArrayList;

public class Cattery {

    private ArrayList<Cat> cats;
    private String businessName;

/**
 * @param Cattery for the Cattery field.
 */

public Cattery() {
    cats = new ArrayList<Cat>();
    this.businessName = businessName;
}

/**
 * Add a cat to the cattery.
 * @param catName the cat to be added.
 */
public void addCat(Cat name)
{
    Cat.add(getName());
}

/**
 * @return the number of cats.
 */
public int getNumberOfCats()
{
    return cats.size();
}
}

最佳答案

只需编辑“addCat”方法即可将对象从参数传递到 ArrayList。

public void addCat(Cat name)
{
    cats.add(name);
}

关于java - 如何将方法调用到对象数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26941350/

相关文章:

java - 在 Java 运行时向最终静态 HashSet 添加(或删除)对象?

java - 如何要求用户输入控制台(BufferedReader)并显示倒计时?需要在两个线程中完成

java - 如何用 Java 编写 GEOTIFF?

arrays - MongoDB:使用索引更新数组中的子文档

arrays - 在Matlab中将矩阵中的元素i,j设置为i^j

java - 如何删除数组列表中的对象

c++ - 传递对对象的引用以进行变异 C++

c# - C# (.NET) 中的 Android AsyncTask 类似功能

java - 创建数组数组的动态数组的最佳方法是什么

javascript - "this"在另一个对象的数组内访问 's "this"- javascript