package pkp;
public class Puke implements Comparable<Puke>{
private String color;
private int points;
public Puke(){
}
public Puke(String color,int points){
this.color=color;
this.points=points;
}
public int compareTo(Puke p){
return this.points - p.points;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
public boolean equals(Object obj){
Puke p = (Puke) obj;
if(this == obj){
return true;
}
if(obj == null){
return false;
}
if(obj instanceof Puke){
return this.color.equals(p.getColor())&&this.points==p.points;
}
return false;
}
public String toString(){
return color+points;
}
}
package pkp;
import java.util.Comparator;
public class ColorComparator implements Comparator<Puke> {
public int compare(Puke p1, Puke p2) {
String [] arr = {"梅花","方片","红桃","黑桃"};
int index1 = 0,index2 = 0;
for(int i = 0;i<arr.length;i++){
if(p1.getColor().equals(arr[i])){
index1 = i;
break;
}
}
for(int j = 0;j<arr.length;j++){
if(p2.getColor().equals(arr[j])){
index2 = j;
break;
}
}
if(index1 != index2){
return index1-index2;
}else {
return p1.getPoints()-p2.getPoints();
}
}
}
package pkp;
import java.util.ArrayList;
import java.util.Collections;
public class TestPuke {
public static void show(ArrayList<Puke> list) {
for(int i=0;i<list.size();i++){
System.out.print(list.get(i)+" ");
if((i+1)%13 == 0){
System.out.print("\n");
}
}
}
public static void main(String[] args) {
ArrayList<Puke> list = new ArrayList<Puke>();
String [] color = {"黑桃","梅花","方片","红桃"};
int [] points = {1,2,3,4,5,6,7,8,9,10,11,12,13};
for (int i = 0; i < color.length; i++) {
for (int j = 0; j < points.length; j++) {
list.add(new Puke(color[i], points[j]));
}
}
show(list);
Collections.shuffle(list);
System.out.println("\n洗牌后:");
show(list);
Collections.sort(list);
System.out.println("\n排序后:");
show(list);
Puke p1 = new Puke("黑桃",5);
Puke p2 = new Puke("黑桃",5);
if(p1.compareTo(p2) == 0){
System.out.println("\n相等");
}else{
System.out.println("\n不相等");
}
Collections.sort(list,new ColorComparator());
System.out.println("\n再次排序后:");
show(list);
}
}