gpt4 book ai didi

java - 如何限制 ArrayList 中的对象数量

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:42:14 25 4
gpt4 key购买 nike

我只是在为我的 O.O.P. 做一些修改。下周就要考试了,我被一个问题困住了。这个问题基本上是举一个狗和跳蚤之间双向关联的例子。到目前为止,我有一只带跳蚤的狗。我坚持的部分是,“修改狗类,使狗对象最多只能容纳 5 个跳蚤对象(打印“你的狗有太多跳蚤!”如果跳蚤超过 5 个)。这是我的代码到目前为止:

狗.java

import java.util.ArrayList;

public class Dog {

private String name;
private int age;
private String address;

ArrayList<Flea> fleas = new ArrayList<Flea>(); {
if(fleas.size() > 5) {
System.out.println("This dog has too many fleas!");
}
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public void hostFlea(Flea flea) {
fleas.add(flea);
}

public ArrayList<Flea> getDogFlea() {
return fleas;
}

public String toString() {
return name + " the Dog (aged " + age + ") has fleas. \nThey are: " + fleas + ".";
}

}

Flea.java

public class Flea {

private String name;
private int age;

public Flea (String name, int age) {
this.name = name;
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String toString() {
return name + " (aged " + age + ")";
}

}

测试.java

public class Test {

public static void main(String[] args) {

Dog dog = new Dog();
dog.setName("Freddy");
dog.setAddress("Cork");
dog.setAge(5);

Flea flea1 = new Flea("John", 1);
dog.hostFlea(flea1);

Flea flea2 = new Flea("Patrick", 3);
dog.hostFlea(flea2);

Flea flea3 = new Flea("Alan", 7);
dog.hostFlea(flea3);

Flea flea4 = new Flea("Steven", 2);
dog.hostFlea(flea4);

Flea flea5 = new Flea("Charles", 5);
dog.hostFlea(flea5);

Flea flea6 = new Flea("Derek", 1);
dog.hostFlea(flea6);

Flea flea7 = new Flea("Kevin", 8);
dog.hostFlea(flea7);

System.out.println(dog);

}

}

控制台:

Freddy the Dog(5 岁)有跳蚤。他们是:[John(1 岁)、Patrick(3 岁)、Alan(7 岁)、Steven(2 岁)、Charles(5 岁)、Derek(1 岁)、Kevin(8 岁)]。

最佳答案

在此处添加检查您的条件:

public void hostFlea(Flea flea) {
if(fleas.size() >= 5) {
System.out.println("This dog has too many fleas!");
} else {
fleas.add(flea);
}
}

不是在你的列表变量的定义中(就像你所做的那样),因为你刚刚添加了 an instance initialization block .

关于java - 如何限制 ArrayList 中的对象数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32039458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com