代码:
public class setExample {
public static void main(String[] args) throws IOException {
HashSet<String> hs = new HashSet<String>();
HashSet<String> hs1 = new HashSet<String>();
int i;
long startTime = 0,midTime = 0;
long endTime = 0, difference, diff;
startTime = System.nanoTime();
for(i = 0; i < 10000000 ; i++)
{
hs.add(i+"");
}
ArrayList<String> arraylist = new ArrayList<String>(hs);
Collections.sort(arraylist);
endTime = System.nanoTime();
difference = endTime - startTime;
System.out.println("Time taken for sorted values in hashset is " +difference);
midTime = System.nanoTime();
for(i = 0; i < 10000000 ; i++)
{
hs1.add((int)(Math.random()*100000000)+"");
}
ArrayList<String> arraylist1 = new ArrayList<String>(hs1);
Collections.sort(arraylist);
long endTime1 = System.nanoTime();
long difference1 = endTime1 - midTime;
System.out.println("Time taken for random values in hashset is " +difference1);
}}
运行上面的代码时,我得到以下输出。为什么生成的随机字符串有问题?
输出:
Time taken for sorted values in hashset is 14334316768
Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded
at java.lang.Integer.toString(Integer.java:308)
at java.lang.Integer.toString(Integer.java:118)
at java.lang.String.valueOf(String.java:2931)
at learn.setExample.main(setExample.java:43)
答案 0 :(得分:0)
因为两个哈希集都有生命周期直到程序结束 因此,添加到哈希集中的数据也不可用于 垃圾收集,因此你可能最终获得outofmememory 错误。
最重要的是,我们正在研究字符串池,我们在其中添加了很多字符串,并且随着字符串池将根据创建的String对象的数量不断增加,因此最终解决方案可能是通过配置-Xmx512m来增加堆大小