manish rout
manish rout

Reputation: 23

why length() is used for getting array's size in json parsing in Android?

while normally we use a length variable for getting size of arrays for example this is a snippet

JSONObject jsonData = new JSONObject(getmData());
JSONArray itemsArray = jsonData.getJSONArray(FLICKR_ITEMS);
for (int i= 0;i<itemsArray.length();i++) {
    JSONObject jsonPhoto =itemsArray.getJSONObject(i);
    String title = jsonPhoto.getString(FLICKR_TITLE);
    String author = jsonPhoto.getString(FLICKR_AUTHOR);
}

Upvotes: 1

Views: 555

Answers (2)

Breavyn
Breavyn

Reputation: 2242

The length member of a normal inbuilt array is final so it can be safely exposed directly. You could try to change it but the compiler won't let you.

A JSONArray however is dynamic which means its length can change by adding or removing items from it. It is not safe to expose the length variable directly because you could change it, likely breaking the object causing exceptions, undefined or unexpected behaviour, etc. For example how would you access the 20th item after you change the length to be 5.

Instead only an accessor method is provided, length(), for getting the length. The length variable is managed internally by the JSONArray class when calling methods that would affect its size such as put() and remove().

You can compare this to a regular List. You get its length by calling its size() method. It is designed like this for the same reason.

Upvotes: 0

Andy Turner
Andy Turner

Reputation: 140484

It's because you're not accessing an array, but rather invoking a method on JSONArray.

It is a bad practice to allow direct field access, since it screws up inheritance, prevents you from controlling who can set its value, forbids synchronization etc when such things are required, so the length field is exposed via a method. See Effective Java 2nd ed Item 14:

In public classes, use accessor method, not public fields

Upvotes: 2

Related Questions