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

 

猜你喜欢

转载自www.cnblogs.com/foxting/p/9429357.html