JAVA HashSet订单 [英] JAVA HashSet Order

查看:61
本文介绍了JAVA HashSet订单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的一次练习代码,

this is my code on one exercise,

public class RockTest {
public static void main(String[] args){
    HashSet<Rock> hashset = new HashSet();
    Rock rock1 = new Rock("QingDanasty",89);
    Rock rock2 = new Rock("Modern",32);
    Rock rock3 = new Rock("MingDanasty",100);

    hashset.add(rock1);
    hashset.add(rock2);
    hashset.add(rock3);

    Iterator<Rock> iterator = hashset.iterator();
    while(iterator.hasNext()){
        System.out.println(iterator.next().getName());
    }
}
}

打印代码时,控制台会显示rock2 rock1 rock3的顺序,而不是rock1 rock2和rock3的顺序,但是,我想知道为什么吗?

When the code gets printed, the console shows the order of rock2 rock1 rock3 instead of rock1 rock2 and rock3 ,however, I wonder why?

推荐答案

HashSet 不保留顺序,如果要保留插入顺序,请使用如果您希望它保留一些比较顺序,请使用自定义比较器 TreeSet

if you want it to preserve some comparative order then use custom Comparator and TreeSet

这篇关于JAVA HashSet订单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆