I have two classes, Foo and Bar. Each Foo has a name and a bunch of items. Bar contains a bunch of Foo’s, each with a unique name.
Bar has a method, AddEntry that takes a fooName and an item (1) if a foo with fooName is already in the Bar, adds another item to the Foo or (2) if a foo with fooName is not in the Bar, creates a Foo with that name and add the item to the new Foo.
This is an outline of how I’m implementing. Is there a better way? I’m just learning Java, but this seems clunky
class Foo { // a name and some items
String fooName;
List<Object> items = new ArrayList<Object>;
Foo(name) {...} // create a named Foo
AddtoFoo(item) {...} // add an item to this Foo
}
class Bar { // a bunch of foo's
List<Foo> fooList = new Arraylist<Foo>;
void AddEntry(String fooName, Object item) {
boolean member = false;
for(Foo foo : fooList){
if{foo.name == fooName) {
member = true;
foo.AddtoFoo(item); // adds an item to this foo
break;
}
}
if(member == false) {
Foo foo = new Foo(fooName); // creates a named foo
foo.AddtoFoo(item); // adds the item
fooList.add(foo); // maintain our list of foo's
}
}
}
I’d use a
Map<String, Foo>to map the foo name to a foo object.Thus you could do