java - How to put a limit on the amount of objects in an ArrayList -
i'm doing revision o.o.p. exam coming next week , i'm stuck on question. question give example of bi-directional association between dog , flea. far i've got dog fleas. part i'm stuck on is, "modify dog class dog object can hold 5 flea objects max (print "your dog has many fleas!" if there's more 5 fleas). here's code far:
dog.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 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 + " 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 + ")"; } }
test.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); } }
console:
freddy dog (aged 5) has fleas. are: [john (aged 1), patrick (aged 3), alan (aged 7), steven (aged 2), charles (aged 5), derek (aged 1), kevin (aged 8)].
add checking condition here:
public void hostflea(flea flea) { if(fleas.size() >= 5) { system.out.println("this dog has many fleas!"); } else { fleas.add(flea); } }
not @ definition of list variable (as did), because added an instance initialization block.
Comments
Post a Comment