I want to sort the objects, and I have applied the approach two ways, however none works. When printing the the content of the arraylist, the elements are in the order they were inserted, and not lexicographically sorted.
I did do research within stackoverlow:
-
In case it works and you want an explanation on anything, I can try to explain it in details! I hope it helps.
CodePudding user response:
You can try adding this code to your
sortPue()
method:public void sortPue() { Collections.sort(pue_ArrayList, new Comparator<Pue>() { public int compare(Pue pp1, Pue pp2) { return pp1.toString().compareTo(pp2.toString()); } }); }
When implementing
Comparator
, you have to specify the types you want to compare, in this case there is<Pue>
. Then, we have to add an implementation for thecompare
method, passing two object references to be compared. In the end,String
'scompareTo
method is used to sort the list.Collections.sort
takes 2 parameters:- the list to be sorted;
- the comparator to determine the order of the list. A null value indicates that the elements' natural ordering should be used.
String
compareTo
returns:- the value
0
if the argument string is equal to this string; - a value
less than 0
if this string is lexicographically less than the string argument; - a value
greater than 0
if this string is lexicographically greater than the string argument.
CodePudding user response:
At a quick glance, this is probably the source of the problem.
Pue tempPue = pue_ArrayList.get(i); pue_ArrayList.set(i, pue_ArrayList.get(j)); pue_ArrayList.set(i, tempPue);
So you take out the i'th element, set the i'th element to something else, then set the i'th element back to what it was. Net result: nothing changed.
Likely that last use of 'i' should be 'j', but I did not analyze this in any detail.