I have three classes I am working with. 1)Category
2)MainCategory
3)SubCategory
Category
: responsible for creating/removing Main CategoriesMainCategory
: respnsible for creating/removing Sub Categories (and nesting them under their respective main categories)SubCategory
: Sets/gets the name of its own instances
The problem that I am having is that when I delete one of my Main Category objects (using .remove) the Sub Categories under it remain and get shifted to the next Main Category. I really want them to be deleted along in case their (Parent) category is has been removed. I point to the problem in the comments in my Main Method at the end of this post. Thank you.
## Category (Class) ##
public class Category {
private ArrayList<MainCategory> mainCat = new ArrayList<MainCategory>();
private String name;
public void addMainCat (MainCategory name){
mainCat.add(name);
}
public ArrayList<MainCategory> returnList() {
return mainCat;
}
public void removeCat(int location){
System.out.println("The Main Category " + mainCat.get(location).getName() + " has been deleted.");
mainCat.remove(location);
}
public void removeCat(MainCategory name){
mainCat.remove(name);
}
}
## MainCategory (Class) ##
public class MainCategory{
private ArrayList<SubCategory> subCat = new ArrayList<SubCategory>();
private String name;
public void addSubCat(SubCategory name){
subCat.add(name);
}
public void removeSubCat(SubCategory name){
subCat.remove(name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ArrayList<SubCategory> returnList(){
return subCat;
}
}
## SubCategory (Class) ##
public class SubCategory{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
## Main (Method) ##
public static void main(String[] args) {
Category stats = new Category();
MainCategory mc1 = new MainCategory();
MainCategory mc2 = new MainCategory();
SubCategory sc1 = new SubCategory();
SubCategory sc2 = new SubCategory();
stats.addMainCat(mc1);
stats.addMainCat(mc2);
mc1.setName("salary");
mc1.addSubCat(sc1);
mc1.addSubCat(sc2);
sc1.setName("mean");
sc2.setName("median");
System.out.println(stats.returnList().get(0).getName());
System.out.println(mc1.returnList().get(0).getName());
stats.removeCat(mc1); // This one is OK.
System.out.println(stats.returnList().get(0).getName()); // Returns null, GOOD!
System.out.println(mc1.returnList().get(0).getName()); // Returns mean (it should return null because mc1 was deleted)
}