zoukankan      html  css  js  c++  java
  • JAVA中的Set

    Set中存放的是没有重复的数据,下说记录一下使用中的小细节。

    1.HashSet

    区分大小写:

    Set<String> set1 = new HashSet<String>();
    Collections.addAll(set1, "A,B,C,D,E,F,G,a,b,c".split(","));
    System.out.println(set1);
    System.out.println(set1.contains("F"));
    System.out.println(set1.contains("f"));
    输出:

    [A, a, B, b, C, c, D, E, F, G]
    true
    false

    BigDecimal比较

     Set<BigDecimal> set2 = new HashSet<BigDecimal>();
     BigDecimal num1 = new BigDecimal("1.0");
     BigDecimal num2 = new BigDecimal("1.00");
     set2.add(num1);
     set2.add(num2);
     System.out.println(set2);

    输出:

    [1.0, 1.00]

    2.TreeSet

    区分大小写:

     Set<String> treeSet = new TreeSet<String>();
     Collections.addAll(treeSet, "A,a,B,b,C,c,D,E,F,G,d,e,f,g,h,i".split(","));
     System.out.println(treeSet);
    

    输出:

    [A, B, C, D, E, F, G, a, b, c, d, e, f, g, h, i]

    如果要不区分大小写,加个参数:

    Set<String> treeSet1 = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
    Collections.addAll(treeSet1, "A,a,B,b,C,c,D,E,F,G,d,e,f,g,h,i".split(","));
    System.out.println(treeSet1);
    输出:
    [A, B, C, D, E, F, G, h, i]
     
    BigDecimal的比较
     Set<BigDecimal> treeSet2 = new TreeSet<BigDecimal>();
     treeSet2.add(num1);
     treeSet2.add(num2);
     System.out.println(treeSet2);
    

    输出:

    [1.0]

    为什么HashSet中加入BigDecimal与TreeSet中加入BigDecimal结算会不一样,这是因为HashSet调用的是equals方法,而Treeset调用的是compareTo方法。他们的实现是不一样的。

     
  • 相关阅读:
    Path Sum II
    Convert Sorted Array to Binary Search Tree
    Construct Binary Tree from Inorder and Postorder Traversal
    Construct Binary Tree from Preorder and Inorder Traversal
    Maximum Depth of Binary Tree
    Binary Tree Zigzag Level Order Traversal
    Binary Tree Level Order Traversal
    Same Tree
    Validate Binary Search Tree
    Binary Tree Inorder Traversal
  • 原文地址:https://www.cnblogs.com/foxting/p/9429357.html
Copyright © 2011-2022 走看看