zoukankan      html  css  js  c++  java
  • HashSet TreeSet 中元素顺序问题(未解决)

    TreeSet HashSet 元素顺序:

    在书上看到:
    HashSet实现了Set接口,使用Hash表来保存元素,因此不能保证元素的获取顺序;
    TreeSet 能对保存的元素进行排序。如果没有指定的排序方式,则按自然顺序排序,对于自然数就是升序排序。

    上机测试,与上述有出入。
    测试代码:

    import java.util.*;
    public class Test {
        public static void main(String args[]){
            Set<Integer> treeSet = new TreeSet<Integer>();
            Set<Integer> hashSet = new HashSet<Integer>();
            for (int i =10 ;i>0;i--) {
                treeSet.add(i);
                hashSet.add(i);
            }
            System.out.println("treeSet= "+treeSet);
            System.out.println("hashSet= "+hashSet);
        }
    }
    
    

    控制台输出:

    > treeSet= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
    > hashSet= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

    HashSet 与 TreeSet 都将元素按照升序输出。
    问题在于 HashSet的输出为何也是按照“一定顺序”输出(测试多次,更改元素添加顺序,但输出均为升序),而非 ”不保证输出顺序”?

    HashSet类继承自AbstractSet抽象类,并且实现Set接口.HashSet类集使用哈希表进行存储,HashSet不保证集合的迭代顺序;特别是HashSet不保证该顺序恒久不变.

  • 相关阅读:
    Python 不同数据类型比较
    计算机外语收集
    d3.js学习-联系力学图
    d3.js学习11
    d3.js学习10
    d3.js学习9
    d3.js学习8
    [springboot jpa] [bug] Could not open JPA EntityManager for transaction
    [spring cloud feign] [bug] 使用对象传输get请求参数
    [ethereum源码分析](5) 创建新账号
  • 原文地址:https://www.cnblogs.com/lingongheng/p/6444232.html
Copyright © 2011-2022 走看看