Zuko
Zuko

Reputation: 2914

Inquiry on some performance tuning

I've got a simple question regarding data structures in Java. if i have a method in Java that returns a data structure say something like this

private List<String> getResults() {
    List<String> data = new ArrayList<String>();
    data.add("One");
    data.add("Two");
    data.add("three");
    data.add("Four");
    return data;
}

and i want to iterate through this list directly as a result from the method like this

 void iterate() {
    for (String value : getResults())
        System.out.println(value);
 }

Would this mean that for every value printed, the method getResults() is always called or is it just cached somewhere in memory and always referenced in this context as opposed to this..

 void iterate() {
    List<String> results = getResults();
    for (String value : results)
        System.out.println(value);
 }

Just extending Knowledge base.Thanx

Upvotes: 0

Views: 33

Answers (1)

Eran
Eran

Reputation: 393821

getResults() is only called once in order to create an Iterator<String> instance, which is later used to retrieve the Strings.

Upvotes: 2

Related Questions