1

我有这段代码可以为不同的卡片组(俱乐部、钻石、红心和黑桃)对我的 arrayLists 进行排序。有没有办法编写以下代码,所以我不必为每个 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);
        }
4

4 回答 4

2

编写自定义方法并为每个集合调用。

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);
于 2013-10-09T13:18:22.503 回答
1

将您的代码分成一个方法:

void sortAndPrint(List<PlayingCard> cards, String label) {
    Collections.sort(cards, new cardIdSorter());
    System.out.printf("%-12s", label);
    for(PlayingCard card: cards) {
        System.out.print(card);
    }
}

然后为每组卡片调用一次该方法:

sortAndPrint(clubs, clubsLabel);
sortAndPrint(diamonds, diamondsLabel);
sortAndPrint(hearts, heartsLabel);
sortAndPrint(spades, spadesLabel);
于 2013-10-09T13:19:30.193 回答
1

定义这样的方法 -

public void sortAndPrint(ArrayList<PlayingCard> cards, String label) {
    Collections.sort(cards, new cardIdSorter());
    System.out.printf("%-12s", label);

    for(PlayingCard card: cards) {
        System.out.print(card);
    }
}

然后这样称呼它-

sortAndPrint(clubs, "Clubs");
sortAndPrint(diamonds, "Diamonds");
sortAndPrint(hearts, "Hearts");
sortAndPrint(spades, "Spades");
于 2013-10-09T13:18:29.620 回答
0

我还没有测试过,但你可能会做这样的事情。

Map<> suites = new HashMap<String, ArrayList<PlayingCard>>() {{
    put("Clubs",clubs); put("Diamonds",diamonds); put("Hearts",hearts); put("Spades",spades);
}};

for (Map.Entry<String, ArrayList<PlayingCard>> entry : suites.entrySet()) {
    Collections.sort(entry.getValue(), new cardIdSorter());
    System.out.printf("%-12s", entry.getKey());
    for(PlayingCard card: entry.getValue()) {
        System.out.print(card);
    }
}

欢迎使用 Java,重构代码以消除重复通常只会让它变得更加丑陋。请注意,这将创建一个新的内部类来进行地图初始化。

于 2013-10-09T13:23:35.083 回答