在Sorting Arrays Using Variables Within the Array找到原始修改后的问题
基本上,我似乎无法找到一种基于eventCodeString
类的Event
对数组进行排序的方法。因为字符串是字母数字(例如A123,B321,C222),传统的比较器(我刚刚发现,感谢原帖中的人)不起作用。我遇到并尝试实施的解决方案越多,我就越困惑。请帮助我理解涉及字符串的数组对象比较的逻辑。
package Chapter9;
import Chapter9.Event;
import javax.swing.JOptionPane;
import java.util.*;
public class EventDemo
{
public static void main(String[] args)
{
callMotto();
int x, sortMethod;
Event[] eventStuff = new Event[8];
for(x = 0; x < 8; ++x)
{
eventStuff[x] = new Event();
eventStuff[x].setEventCodeString();
eventStuff[x].setGuests();
eventStuff[x].setContactNumber();
eventStuff[x].setEventStr();
}
//Sorting method start
do
{
String sorting;
sorting = JOptionPane.showInputDialog("Please choose sorting method:\n"
+ "1 to sort by event number\n"
+ "2 to sort by number of guests\n"
+ "3 to sort by event type\n"
+ "Type 99 to exit sorting list");
sortMethod = Integer.parseInt(sorting);
//Event code sorting start
if(sortMethod == 1)
{
for(x = 0; x < 8; ++x)
{
}
}
//Event code sorting end
if(sortMethod == 2)
{
for(x = 0; x < 8; ++x)
{
Arrays.sort(eventStuff, new Comparator<Event>()
{
@Override
public int compare(Event o1, Event o2)
{
if (o1.getGuests() < o2.getGuests())
return -1;
else if (o1.getGuests() == o2.getGuests())
return 0;
else
return 1;
}
});
eventStuff[x].largeParty();
}
}
//Event type sorting start
if(sortMethod == 3)
{
for(x = 0; x < 8; ++x)
{
Arrays.sort(eventStuff, new Comparator<Event>()
{
@Override
public int compare(Event o1, Event o2)
{
if (o1.getEventStr() < o2.getEventStr())
return -1;
else if (o1.getEventStr() == o2.getEventStr())
return 0;
else
return 1;
}
});
eventStuff[x].largeParty();
}
//Event type sorting end
//Sorting method end
}
if(sortMethod == 99)
System.exit(0);
}
while(sortMethod != 99);
}
public static void callMotto()
{
JOptionPane.showMessageDialog(null, "*******************************************************\n"
+ "* Carly's Makes The Food That Makes The Party! *\n"
+ "*******************************************************");
}
}
答案 0 :(得分:2)
仅仅因为您无法使用String
来比较==
,您应该使用String#equals
代替<
。 <=
,!=
,>
,>=
和Arrays.sort(eventStuff, new Comparator<Event>() {
@Override
public int compare(Event o1, Event o2)
{
if (o1.getEventStr() < o2.getEventStr())
return -1;
else if (o1.getEventStr() == o2.getEventStr()) // this line
return 0;
else
return 1;
}
});
也是如此。
您可以参考this other StackOverflow question进行解释。
也就是说,你必须替换:
Arrays.sort(eventStuff, new Comparator<Event>() {
@Override
public int compare(final Event o1, final Event o2) {
return o1.getEventStr().compareTo(o2.getEventStr));
}
});
由:
String#compareTo(String)
String
方法来自Java Comparable<String>
实现Comparator
的事实,这基本上意味着它们本身就知道如何比较它们。
由于我对此有所建议,我建议您也更改访客号码if (o1.getGuests() < o2.getGuests())
return -1;
else if (o1.getGuests() == o2.getGuests())
return 0;
else
return 1;
的实施情况:
return o1.getGuests() - o2.getGuests;
可能会成为:
o1.getGuests() < o2.getGuests()
如果你考虑一下,它确实会:
o1.getGuests() == o2.getGuests()
o1.getGuests() > o2.getGuests()
......这正是我们所需要的:)