sorting - Sort objects highest-lowest in Java with ArrayList? -
write method return toy occurs in list frequent , method sort toys count.
this code
import java.util.arraylist; public class toystore { private arraylist<toy> toylist; public toystore() { } public void loadtoys(string toys) { toylist = new arraylist<toy>(); (string item : toys.split(" ")) { toy t = getthattoy(item); if (t == null) { toylist.add(new toy(item)); } else { t.setcount(t.getcount() + 1); } } } public toy getthattoy(string nm) { (toy item : toylist) { if (item.getname().equals(nm)) { return item; } } return null; } public string getmostfrequenttoy() { int position = 0; int maximum = integer.min_value; (int = toylist.size() - 1; >= 0; i--) { if (toylist.get(i).getcount() > maximum) maximum = toylist.get(i).getcount(); position = i; } return toylist.get(position).getname(); } public void sorttoysbycount() { arraylist<toy> t = new arraylist<toy>(); int count = 0; int size = toylist.size(); (int = size; > 0; i--) { t.add(new toy(getmostfrequenttoy())); t.get(count).setcount(getthattoy(getmostfrequenttoy()).getcount()); toylist.remove(getthattoy(getmostfrequenttoy())); count++; } toylist = t; } public string tostring() { return toylist + "" + "\n" + "max == " + getmostfrequenttoy(); } } here method care about
public void sorttoysbycount() { arraylist<toy> t = new arraylist<toy>(); int count = 0; int size = toylist.size(); (int = size; > 0; i--) { t.add(new toy(getmostfrequenttoy())); t.get(count).setcount(getthattoy(getmostfrequenttoy()).getcount()); toylist.remove(getthattoy(getmostfrequenttoy())); count++; } toylist = t; } here output
[sorry 4, bat 1, train 2, teddy 2, ball 2] here want
[sorry 4, train 2, teddy 2, ball 2, bat 1]; what wrong in code? how do it?
the problem in getmostfrequenttoy() method:
replace
if (toylist.get(i).getcount() > maximum) maximum = toylist.get(i).getcount(); position = i; with
if (toylist.get(i).getcount() > maximum) { maximum = toylist.get(i).getcount(); position = i; } because want position corresponds maximum.
Comments
Post a Comment