ComeçarComece de graça

Implementing memory-efficient string processing

You're developing a text processing application that needs to pre-populate an array with the same string value multiple times. The current implementation creates a new String object in each loop iteration, which is inefficient for large arrays. Your task is to implement a more efficient version of this method.

Este exercício faz parte do curso

Optimizing Code in Java

Ver curso

Instruções do exercício

  • Reuse the provided value to add to the list.
  • Return the final array.

Exercício interativo prático

Experimente este exercício completando este código de exemplo.

public class ArrayPopulation {
    
    public static void main(String[] args) {
        int size = 10000;

        String[] inefficientArray = populateArrayInefficient(size, "DataCamp");
        String[] efficientArray = populateArrayEfficient(size, "DataCamp");

        System.out.println("Arrays have same length: " + (inefficientArray.length == efficientArray.length));
    }

    public static String[] populateArrayInefficient(int size, String value) {
        String[] array = new String[size];
        
        for (int i = 0; i < size; i++) {
            String stringValue = new String(value);
            array[i] = stringValue;
        }
        
        return array;
    }

    public static String[] populateArrayEfficient(int size, String value) {
        String[] array = new String[size];
        
        for (int i = 0; i < size; i++) {
            // Reuse the same String object
            ____
        }
        
        // Return the final array
        return ____;
    }
}
Editar e executar o código