I’ve read a few tutorials on customizing Arrays.sort, and a lot of googling, but I’m missing the answer. Right now Arrays.sort(charList) does nothing. Here’s what my code looks like.
public class character implements Comparable<character>{
//public vars
public String charName;
public int initModifier;
public int initRoll;
public int secondInit;
/* ... getters, setters, other vars .. */
@Override
public int compareTo(character another) {
int compareInit = ((character) another).getTotalInit();
int comp = this.totalInit - compareInit;
int compareSecondInit = ((character) another).getTotalInit();
if (comp != 0)
{
return comp;
}
else
{
return this.secondInit - compareSecondInit;
}
}
}
The main activity is a bundle of stuff. The part that deals with the arrays.sort follows:
//add a character to the array.
public void addResults(character c)
{
debugInt++; //using this to debug
if(debugInt==3)
{
Log.d(tag,charList[0].charName); //always prints the first object entered
Log.d(tag,charList[1].charName); //always prints the second object entered
}
if (playersPerTurn<charLimit)
{
charList[playersPerTurn]=c;
Arrays.sort(charList,0,playersPerTurn);
playersPerTurn++;
updateDisplay();
}
}
Help me SO, you’re my only hope.
You probably wanted
getSecondInit()here.Your
compareTo()with this bug is not consistent – and thus the result is undefined.for example:
As a side note, about coding practice:
characteris confusing, you should consider renaming it.characteris a class and not a field.