Search code examples
javaloopsvariablesarraylistlocal

How do I loop through an array list and display the elements stored without a system.out.println statement?


So I am having trouble trying to loop through an array list but i dont want to use a println statement to print the elements from the array list. Is it possible if i could store all the elements into a local variable through each loop and then return the local variable when i call the method later on?e Here is my code:

public String displayProperties() {
        String property = null;
        for (int i = 0; i < properties.size(); i++) {
            property = properties.get(i);
        }
        return property;     
    }


Solution

  • You would have to introduce an instance variable in order to cache the result of your method (your local variable doesn't live past the current execution of the method).

    And you'd also need to change the logic of that method, to append all the elements into a single String.

    I also suggest adding some separator between the elements.

    private String cachedProperties = null;
    public String displayProperties() {
        if (cachedProperties == null) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < properties.size(); i++) {
                if (i > 0) {
                    sb.append(',');
                }
                sb.append(properties.get(i));
            }
            cachedProperties = sb.toString();
        }   
        return cachedProperties;
    }
    

    Note that if the properties List may change, you have to reset your cache instance variable each time that happens.