是否可以对对象数组进行冒泡排序?
我有一个由 .txt 文件填充的对象数组
Object[] punteggiTutti = scores.toArray();
即使可以使用 .sort 函数:
Arrays.sort(punteggiTutti, Collections.reverseOrder());
我会知道如何应用有效的冒泡排序算法;我尝试了以下不起作用的代码:
for(int i=0; i<j; i++)
{
if(punteggiTutti[i]<punteggiTutti[i+1]) // error "<" operator cannot be used in objects
{
temp=punteggiTutti[i];
punteggiTutti[i]=punteggiTutti[i+1];
punteggiTutti[i+1]=temp;
}
}
I have an array of objects populated by a .txt file
Object[] punteggiTutti = scores.toArray();
Even if it's possible to use the .sort function:
Arrays.sort(punteggiTutti, Collections.reverseOrder());
I would know how to apply a working bubblesort algorithm; I tried the following not working code:
for(int i=0; i<j; i++)
{
if(punteggiTutti[i]<punteggiTutti[i+1]) // error "<" operator cannot be used in objects
{
temp=punteggiTutti[i];
punteggiTutti[i]=punteggiTutti[i+1];
punteggiTutti[i+1]=temp;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能使用 < 来比较两个对象操作员。
使用实现 Comparable 接口的东西。然后可以使用函数 a.compareTo(b); 来比较这些元素。
http://download.oracle.com/javase /1.5.0/docs/api/java/lang/Comparable.html
另请参阅:
http://leepoint.net/notes-java/data/expressions/22compareobjects.html
尝试阅读有关 Java 中的相等性的内容。这应该可以帮助您解决将来使用 Java 时出现的错误。
You can't compare two Objects with < operator.
Use something which implements Comparable interface. Then such elements can be compared using function a.compareTo(b);
http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Comparable.html
Also have a look at:
http://leepoint.net/notes-java/data/expressions/22compareobjects.html
Try to read about equality in Java. This should help you with future errors when using Java.
为您的对象创建一个比较器,以将一个对象与另一个对象进行比较。
内置的归并排序算法比冒泡排序快得多。
http://www.iti.fh-flensburg.de /lang/algorithmen/sortieren/sortcontest/sortcontest.htm
http://www.sorting-algorithms.com/
Create an Comparator for your object, to compare on object against the other.
The built in mergeSort algorithm is much faster than bubblesort.
http://www.iti.fh-flensburg.de/lang/algorithmen/sortieren/sortcontest/sortcontest.htm
http://www.sorting-algorithms.com/