package test.meiju;
public class Poker implements Comparable<Poker>{
private int value;//值
private String name;//名字
private Type type;
public static enum Type{
黑桃(4),红桃(3),草花(2),方片(1);
private int v;
Type(int v){
this.v=v;
}
public int getV(){
return this.v;
}
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
@Override
public int compareTo(Poker o) {
if(this.value==o.value){
return this.type.v-o.type.v;
}else{
return this.value-o.value;
}
}
@Override
public String toString() {
return "Poker [value=" + value + ", name=" + name + ", type=" + type + "]\n";
}
}
创建一个扑克类,然后再创建一个扑克盒,用set存储。
使用Collections的shuffle和sort进行排序。
自定义比较器
package test.meiju;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class PokerBox {
private Set<Poker> pokers;
public Set getPokers(){
return pokers;
}
public PokerBox(){
pokers=new TreeSet<>();
int index=0;
for(int i=1;i<=13;i++){
for(Poker.Type pt:Poker.Type.values()){
Poker p=new Poker();
p.setValue(i);//设置值 1~ 13
p.setType(pt);// 设置花色 4个
switch(i){
case 1:p.setName(pt.name()+"A"); break;
case 11:p.setName(pt.name()+"J");break;
case 12:p.setName(pt.name()+"Q");break;
case 13:p.setName(pt.name()+"K");break;
default : p.setName(pt.name()+i);
}
pokers.add(p);
}
}
}
public void shufflePoker(List<Poker> list){
Collections.shuffle(list);
}
public void showPokers(){
System.out.println(pokers);
}
public void sort(List<Poker> pokers){
Collections.sort(pokers);
}
public static void main(String[] args) {
PokerBox pb=new PokerBox();
List<Poker> list=new LinkedList<>(pb.getPokers());
//pb.showPokers();
pb.shufflePoker(list);
System.out.println(list);
pb.sort(list);
System.out.println(list);
}
}