2 回答
TA贡献2041条经验 获得超4个赞
请尝试此代码是否对您有帮助。
import java.util.*;
class CustomComparator implements Comparator<String> {
final String ORDER= "23456789TJQKA";
public int compare(String a, String b) {
return ORDER.indexOf(a) - ORDER.indexOf(b) ;
}
}
public class SortIt {
public static void main(String[] args) {
List cards = new ArrayList<>(Arrays.asList("K", "A", "7", "Q", "6", "J", "T"));
Collections.sort(cards, new CustomComparator());
System.out.println(cards);
}
}
输出:
[6, 7, T, J, Q, K, A]
TA贡献1804条经验 获得超7个赞
如果我是你,我会使用它。这只是另一个答案,如果复杂性对您来说并不重要,您可以使用它。也许你对你的其他项目有一个想法。
public List<String> sort(String[] cards) {
for (int i = 0; i < cards.length; i++) {
switch (cards[i]) {
case "T":
cards[i] = "91";
break;
case "J":
cards[i] = "92";
break;
case "Q":
cards[i] = "93";
break;
case "K":
cards[i] = "94";
break;
case "A":
cards[i] = "95";
break;
}
}
Arrays.sort(cards);
for (int i = 0; i < cards.length; i++) {
switch (cards[i]) {
case "91":
cards[i] = "T";
break;
case "92":
cards[i] = "J";
break;
case "93":
cards[i] = "Q";
break;
case "94":
cards[i] = "K";
break;
case "95":
cards[i] = "A";
break;
}
}
return Arrays.asList(cards);
}
添加回答
举报