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方法。他们的实现是不一样的。

     
  • 相关阅读:
    微信支付开发(12) 认清微信支付v2和v3
    教爸爸妈妈用微信
    微信公众平台开发(103) 四六级成绩查询
    微信支付开发(11) Native支付
    微信公众平台开放设备接入能力
    微信公众平台开发(102) 模板消息
    微信支付开发(10) 全网发布
    微信小店开发(3) 自定义菜单加入维权
    openssl下载
    使用PHP QR Code生成二维码
  • 原文地址:https://www.cnblogs.com/foxting/p/9429357.html
Copyright © 2011-2022 走看看