I am trying to write public instance method createParther() that returns an instance of Couple. The method does its job by following these rules: one dancer in the couple must be from aList and the other bList, one dancer in the couple must be male and the other female. Neither dancer in the couple should be partnered already. If it is not possible to create a couple from amongst the unpartnered dancers, then null should be returned. If an instance of Couple is successfully created, both dancers involved in the couple should have their partnered instance variables set to true. I have attempted to list all the aList and bList to together, but then I didn’t know to check the requirements as per above. Can anyone demostrate how this could be acheieved? This is not assignment.
public class FoxDancing
{
private List<Couple> coupleList;
private List<Dancer> aList;
private List<Dancer> bList;
public FoxDancing()
{
couplesList = new ArrayList<Parthers>();
aList = new ArrayList<Dancer>();
bList = new ArrayList<Dancer>();
}
public void fieldLists()
{
this.addX("Simon","AList",'m');
this.addX("Jason","AList",'m');
this.addX("Ian","AList",'m');
this.addX("Susan","BList",'f');
this.addX("Helena","BList",'f');
this.addX("Gina","BList",'f');
}
}
It looks like you’d want to have a helper method like this:
This uses a “foreach loop” for a concise, readable iteration over all
Dancerin theList<Dancer>.Then you can write something like this:
While this should work, note that
findUnpartneredis aO(N)linear search. If the list is of any considerable length, consider having alternative data structures, e.g. aSet<Dancer>that partitions the list into unpartnered and partnered subsets.On generics invariance
You’ve written the following:
This will not compile. A
List<Partner>(assuming this is what you meant to write) is NOT aList<Couple>. Perhaps you want anew ArrayList<Couple>, or ifPartneris a subtype ofCouple, then perhaps you want aList<? extends Couple> coupleList.Related questions
<E extends Number>and<Number>?See also
On
enumYou’ve written the following:
I don’t know much about Foxtrot dancing, but if there’s a conceptual A-list and B-list , then you may consider using an
enuminstead ofStringmarkers"AList"and"BList". Similarly, if there can only be male or female dancers, thenenumwould be much better than'm'and'f'.See also
Related questions