我有这段代码可以根据不同的牌组(梅花、方 block 、红心和黑桃)对数组列表进行排序。有什么方法可以编写以下代码,这样我就不必为每个 ArrayList 都编写它了吗?
String clubsLabel = "Clubs";
String diamondsLabel = "Diamonds";
String heartsLabel = "Hearts";
String spadesLabel = "Spades";
Collections.sort(clubs, new cardIdSorter());
System.out.printf("%-12s", clubsLabel);
for(PlayingCard clubsCard: clubs) {
System.out.print(clubsCard);
}
System.out.println(" ");
Collections.sort(diamonds, new cardIdSorter());
System.out.printf("%-12s", diamondsLabel);
for(PlayingCard diamondsCard: diamonds) {
System.out.print(diamondsCard);
}
System.out.println(" ");
Collections.sort(hearts, new cardIdSorter());
System.out.printf("%-12s", heartsLabel);
for(PlayingCard heartsCard: hearts) {
System.out.print(heartsCard);
}
System.out.println(" ");
Collections.sort(spades, new cardIdSorter());
System.out.printf("%-12s", spadesLabel);
for(PlayingCard spadesCard: spades) {
System.out.print(spadesCard);
}
最佳答案
为每个集合编写自定义方法并调用。
public static void sortAndPrintCollection(Collection col,String var){
Collections.sort(col, new cardIdSorter());
System.out.printf("%-12s", var);
for(PlayingCard p: col) {
System.out.print(p);
}}
使用示例
ClassName.collectionSorter(clubs,clubsLabel);
关于java - 我如何将这些 java collection.sort 语句合并为一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19273132/