• HashSet Integer输出有序,String输出无序


    1. 背景
    自己在测试HashSet时,发现其输出Integer是有序的。
    2. 测试
    public static void hashSetObjectTest(){


    Set<Integer> set = new HashSet<Integer>();

     

    set.add(6);

        set.add(3);

        set.add(2);

        set.add(1);

        set.add(4);  

        set.add(5);

        //set.add(100);

        //set.add(130);

        //set.add(22);

         

        System.out.println("-------hashset 输出有序结果---------");  

         

        for(Integer value : set){  

                System.out.print(value+" ");  

        }

         

        System.out.println();  

    }



    3. 结果
    -------hashset 输出有序结果---------

    1 2 3 4 5 6



    4. 分析
    这是一种假象,数据少可能这样,但是数据多了,就无序了。
    4.1 测试
    public static void hashSetObjectTest(){
            
    <span style="white-space:pre">    </span>     Set<Integer> set = new HashSet<Integer>();
            
             set.add(6);
             set.add(3);
             set.add(2);
             set.add(1);
             set.add(4);  
             set.add(5);
             set.add(100);
             set.add(130);
             set.add(22);
             
             System.out.println("-------hashset 输出有序结果---------");  
             
             for(Integer value : set){  
                    System.out.print(value+" ");  
             }
             
             System.out.println();  
        }
    4.2 结果
    -------hashset 输出有序结果---------
    1 100 2 3 4 5 6 22 130

    所以测试时,最好多测一点数据。
    4.3 java api说明
    This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.

    该类实现了Set接口,通过hash table实现。HashSet的迭代器在输出时“不保证有序”,但也不是“保证无序”。也就是说,输出时有序也是允许的,但是你的程序不应该依赖这一点。

  • 相关阅读:
    Spring中配置和读取多个Properties文件
    python 数据清洗
    python excel 文件合并
    Pandas -- Merge,join and concatenate
    python 数据合并
    python pandas
    python Numpy
    EXCEL 导入 R 的几种方法 R—readr和readxl包
    R语言笔记完整版
    第十三章 多项式回归分析
  • 原文地址:https://www.cnblogs.com/zhuyeshen/p/12081371.html
Copyright © 2020-2023  润新知