简体   繁体   English

Java - OutOfMemoryError:Java 堆空间

[英]Java - OutOfMemoryError : Java heap space

I'm trying to create an string arraylist with a size 100,000, wherein every element after the first two is the previous two strings concatenated.我正在尝试创建一个大小为 100,000 的字符串数组列表,其中前两个之后的每个元素都是连接的前两个字符串。 The problem is, I run out of memory before I even reach 100 strings.问题是,我什至在达到 100 个字符串之前就耗尽了内存。 I plan to use this arraylist to do a binary search and output a letter in the string based on the input given, which is the index of the string, and the index of the letter within the string.我打算使用这个数组列表进行二分搜索,并根据给定的输入输出字符串中的一个字母,这是字符串的索引,以及字符串中字母的索引。

Here's the code这是代码

    public static void generateSequence(int numStrings, ArrayList<String> input){
        String temp = "", S1, S2;
        for(int i = 0; i < n; i++) {
            if(i == 0) {
                input.add("H");
            }
            else if(i == 1) {
                input.add("A");
            }
            else {
                S1 = input.get(input.size() - 2);
                S2 = input.get(input.size() - 1);
                temp = S1.concat(S2);
                input.add(temp);
                temp = "";
            }
        }
    }

I'm not sure how to be more efficient with the memory usage to get the arraylist I need for this, so any advice would be helpful.我不确定如何更有效地使用内存来获取我需要的数组列表,所以任何建议都会有所帮助。 Thank you.谢谢你。

So the N th element is the concatenation of the N-1 th and N-2 th elements?那么第 N元素是第 N-1和第 N-2元素的串联吗?

Thus the length of the N th element is the sum of the lengths of the two previous elements.因此,第 N元素的长度是前两个元素的长度之和。

You're talking about a huge amount of storage.你说的是大量的存储空间。 This code shows you how much storage the N th entry needs.此代码向您显示第 N条目需要多少存储空间。

    double n0 = 1, n1 = 1;
    for (int i=2; i<=100; i++) {
        double n2 = n1 + n0;
        System.out.printf("%4d : %e\n", i, n2);
        n0 = n1;
        n1 = n2;
    }

The 49th entry has 12 billion characters (so that's about 24 billion characters overall; or about 48 GB).第 49 个条目有 120 亿个字符(总共大约 240 亿个字符;或大约 48 GB)。

The 100th entry (counting from 1) has over 5 x 10 20 characters.第 100 个条目(从 1 开始计数)有超过 5 x 10 20 个字符。

You need to rethink your data structure.你需要重新考虑你的数据结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM