Java TreeSet集合排序的规则


package itheima_04;

import java.util.*;

public class PokerDemo {
    public static void main(String[] args) {
        //创建HashMap,健是编号,值是牌
        HashMap<Integer,String>hm = new HashMap<Integer,String>();
        //创建Arraylist储存编号
        ArrayList<Integer>array = new ArrayList<Integer>();
        //创建花色和点数数组
        //定义花色数组 ,定义点数数组
        String[] colors = {"♦","♥","♣","♠"};
        String[] numbers = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"};
     **   //从0开始HashMap里面储存编号,并储存对应的牌。同时往ArrayList里面储存编号
        int index = 0;
        for(String number: numbers){//这里嵌套数字一定要在外层,
            for(String color:colors){
                hm.put(index,color+number);//每一个编号都对应了一张牌,再把编号储存起来,再分发编号找对应的牌
                array.add(index);
                index++;**
            }
        }
        hm.put(index,"小王");//上面的for结尾判断时多加了一次编号
        array.add(index);
        index++;
        hm.put(index,"大王");
        array.add(index);
        //洗牌(洗的是编号),用collertions的shuffle()方法实现
        Collections.shuffle(array);
        //发牌(发的也是编号,为了保证编号是排序的,创建TreeSet集合接收)
        TreeSet<Integer> lhc = new TreeSet<Integer>();
        TreeSet<Integer>dfbb = new TreeSet<Integer>();
        TreeSet<Integer>wh = new TreeSet<Integer>();
        TreeSet<Integer>dp = new TreeSet<Integer>();
        for(int i=0;i<array.size();i++){
            if(i>=array.size()-3){
                dp.add(array.get(i));
            }else if(i%3==0){
                lhc.add(array.get(i));
            }else if(i%3==1){
                dfbb.add(array.get(i));
            }else if(i%3==2){
                wh.add(array.get(i));
            }
        }
        //看牌,遍历三位玩家的编号,并且找对应的值
        lookPoker("令狐冲",lhc,hm);
        lookPoker("东方不败",dfbb,hm);
        lookPoker("温华",wh,hm);
        lookPoker("底牌",dp,hm);
    }
    //定义方法看牌(遍历Treeset集合,获取编号,到hashmap集合中找对应的牌
    public static void lookPoker(String name,TreeSet<Integer>ts,HashMap<Integer,String>hm){//需要用到编号和值
        System.out.print(name + "的牌是:");
        for(Integer key:ts){
            String poker = hm.get(key);//遍历时找编号对应的牌
            System.out.print(poker +" ");//找到对应的牌之后输出
        }
        System.out.println();
    }
}

为啥数字一定在嵌套的外层?存入TreeSet集合的只是index啊,到后面排序时,也只是排序index啊,我这这里把花色放在外层它就排不了序了。求解释一下

如果数字在外层,存储在hashmap里面的数据顺序是这样的:
♦️3,♥️3,♣️3,♠️3,♦️4,♥️4,♣️4,♠️4,♦️5,♥️5,♣️5,♠️5……
所以按顺序取的时候数字是有序的
如果数字在内层,存储在hashmap里面的数据顺序是这样的:
♦️3,♦️4,♦️5,♦️6,♦️7,♦️8……
所以取的时候花色是有序的,而数字是无序的

另外,说明一下,如果hashmap的key存储的是有序的数字,那打印的时候也是有序的,但还是不记录添加顺序

你试试接入比较器接口,重写run方法,然后把你想要他如何排序写一下就可以了