我有三个ArrayLists.字符串之一 – 名称和两个整数 – 得分和图片编号.我想通过球员得分(从最高到最低)同时对它们进行排序.现在我使用一个简单的冒泡排序,但我认为当列表更大时它将不会有效.
这是我的代码:
public class MyBubbleSort { public static voID bubble_srt(List<Integer> score, List<String> name, List<Integer> pic) { int n = score.size(); int k; for (int m = n; m >= 0; m--) { for (int i = 0; i < n - 1; i++) { k = i + 1; if (score.get(i) < score.get(k)) { swapNumbers(i, k, score, name, pic); } } printNumbers(score); } } private static voID swapNumbers(int i, int j, List<Integer> score, List<String> name, List<Integer> pic) { int temp; temp = score.get(i); score.set(i, score.get(j)); score.set(j, temp); String s; s = name.get(i); name.set(i, name.get(j)); name.set(j, s); int p; p = pic.get(i); pic.set(i, pic.get(j)); pic.set(j, p); } private static voID printNumbers(List<Integer> input) { for (int i = 0; i < input.size(); i++) { System.out.print(input.get(i) + ", "); } System.out.print("\n"); }}
谢谢!
解决方法:
首先创建一个PlayerInfo类,如下所示:
package test;public class PlayerInfo { private String name; private Integer score; private Integer pictureID; public PlayerInfo(final String name, final Integer score, final Integer pictureID) { this.name = name; this.score = score; this.pictureID = pictureID; } public String getname() { return this.name; } public voID setname(final String name) { this.name = name; } public Integer getscore() { return this.score; } public voID setscore(final Integer score) { this.score = score; } public Integer getPictureID() { return this.pictureID; } public voID setPictureID(final Integer pictureID) { this.pictureID = pictureID; } @OverrIDe public String toString() { return this.name + ":" + this.score + ":" + this.pictureID; }}
第二个创建一个PlayerInfo比较器.在这里,我们创建一个scoreBasedComparator(根据您的要求,但您也可以创建其他比较器以满足您的特定需求):
package test;import java.util.Comparator;public class scoreBasedComparator implements Comparator<PlayerInfo> { @OverrIDe public int compare(final PlayerInfo playerInfo1, final PlayerInfo playerInfo2) { return playerInfo1.getscore().compareto(playerInfo2.getscore()); }}
最后,您可以使用Collections.sort(< your collection>,< your comparator>)对您的PlayerInfo实例列表进行排序,如下所示:
package test;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.List;public class Runner { public static voID main(final String[] args) { List<PlayerInfo> playerInfos = new ArrayList<PlayerInfo>(); playerInfos.add(new PlayerInfo("A", 123, 1)); playerInfos.add(new PlayerInfo("B", 1, 2)); playerInfos.add(new PlayerInfo("C", 23, 3)); playerInfos.add(new PlayerInfo("D", 300, 4)); Collections.sort(playerInfos, new scoreBasedComparator()); System.out.println(Arrays.toString(playerInfos.toArray())); }}
运行这个小程序将输出以下行:
[B:1:2, C:23:3, A:123:1, D:300:4]
如您所见,您的收藏在创建时未分类,但按打分排序打印.
希望这可以帮助.
总结以上是内存溢出为你收集整理的在Java中同时对三个ArrayLists进行排序的最有效方法是什么?全部内容,希望文章能够帮你解决在Java中同时对三个ArrayLists进行排序的最有效方法是什么?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)