[java]HashSet删除null元素

来源:互联网 发布:pdf.js 跨域访问文件 编辑:程序博客网 时间:2024/06/10 09:20
原文链接:http://blog.sina.com.cn/s/blog_793f9856010115id.html
最近使用到HashSet,对象中明明没有元素,但对象的size就是为1,查了一下,
http://www.java2s.com/Tutorial/Java/0140__Collections/SetandHashSet.htm上有说,
  1. HashSetallowsat most one nullelement.
  2. HashSet is faster than other implementations of Set, TreeSetand LinkedHashSet.
那么如何删除这个空元素呢?cal is an object of HashSet.
1.最先想到的,cal.remove(null);没有效果。
2.Iteratorhs;hs = cal.iterator();Object o = hs.next();
if((String)o!="") t+=1;
得到的o不知道为什么是一个很长的字符串而不是"",未成功。
3.google了一下java how todelete the null element from hashset 
http://www.java-community.de/archives/12-How-to-remove-all-null-elements-from-a-Collection.html给了两个方法。满怀信心测试了下,也没有效果。

4.一切方法都没有效果之后,随便写了一个小例子测试了下,上述方法都可以删除空元素。输入+处理+输出,处理和输出过程都一样,哪肯定是对象的数据源有问题了。
仔细检查cal对象(从一个文件中读取),原来该文件格式时utf8-with bom,有一个bom文件头,将文件格式改为utf8-without bom即可了!