Reputation: 382
I want to write a method for a package to get the contained classes in a hierarchical structure like this, but for an indefinite number of supertypes. Where the methods with no supertypes are in the beginning of the list and they're extending classes in the end.
My approach is inspired by bubble sort and checks if the neighbour is one of the supertypes and swaps the classes if so.
List<GenClass> getOrderedGenClasses() {
List<GenClass> classes = new ArrayList<>(getGenClasses()); //the unordered classes
for (int i=0; i<classes.size(); i++){ //the bubble sort approach to check e
for (int j=i+1; j<classes.size(); j++){
List<GenClass> superclasses = classes.get(i).getBaseGenClasses(); //gets the superclasses for comparison
for(int k=0; k<superclasses.size();k++) { //just checks if the superclass is contained
if (superclasses.get(k).getName() == classes.get(j).getName()){
Collections.swap(classes, i, j); //if it is contained swap the neighbours
break;
}
}
}
}
return classes;
}
For some classes it works, but some are still not in the right order. What am I doing wrong?
Upvotes: 0
Views: 49
Reputation: 140525
The actual problem could be here:
superclasses.get(k).getName() == classes.get(j).getName()
You compare strings using the equals() method; not by using == !!!
But beyond that, the essential answer (to "what am I doing wrong here") is: you are not using TDD.
TDD is a perfect technique for such problems. You see, you have (hopefully) very clear requirements.
You could/should by "simply" making your requirements explicit by putting them into a testcase. Then you add the code to fulfill that test. Then you write the next test. On and on ...
That simply avoids the situation you are facing right now: you have a bunch of (complicated) production code, it seems to work sometimes, but not "all the time". And you have no idea where to start.
But lets give you some more concrete advise: look into separating concerns. You are mixing up different responsibilities within that code.
You should have one method/class that "collects" all classes/interfaces from a package. No ordering, just make sure you get exactly those classes you want to be found.
And then, you write code that somehow works on that collection. By doing so, you also make it easier to come up with small, crisp tests - it is easier to test a "class" collector", versus testing a "sorting class collector".
Upvotes: 1