user786
user786

Reputation: 4364

Java code explanation required, method void return type and calling method variable

I came across this Java code and I am a bit confused.

Following is the code

public ArrayList<GalleryItem> fetchItems() {
    ArrayList<GalleryItem> items = new ArrayList<GalleryItem>();

    try {
        ....

        parseItems(items, parser);
    } catch (IOException ioe) {
        Log.e(TAG, "Failed to fetch items", ioe);
    } catch (XmlPullParserException xppe) {
        Log.e(TAG, "Failed to parse items", xppe);
    }
    return items;
}


void parseItems(ArrayList<GalleryItem> items, XmlPullParser parser) throws XmlPullParserException, IOException {
    int eventType = parser.next();

    while (eventType != XmlPullParser.END_DOCUMENT) {
        if (eventType == XmlPullParser.START_TAG &&
            ....
            item.setId(id);
            item.setCaption(caption);
            item.setUrl(smallUrl);
            items.add(item);
           ...
        }
        eventType = parser.next();
    }
}

What I need to know is: in above code, items is passed to void parseitems(...) method. As you can see the parseitems method has return type void. After parsing, the items in fetchItems method got the values. How is it possible? explanation please

Upvotes: 0

Views: 77

Answers (1)

MaxG
MaxG

Reputation: 1077

You have to know that in java, Objects are passed to methods by reference. This means that parseItems is changing the actual Object that its local reference points to.

Actually the real story is a bit more interesting: What you actually pass to the method as a parameter is the reference by value.

Upvotes: 4

Related Questions