简体   繁体   中英

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. The problem is, I run out of memory before I even reach 100 strings. 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?

Thus the length of the N th element is the sum of the lengths of the two previous elements.

You're talking about a huge amount of storage. This code shows you how much storage the N th entry needs.

    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).

The 100th entry (counting from 1) has over 5 x 10 20 characters.

You need to rethink your data structure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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