eggHunter
eggHunter

Reputation: 389

Size has private access in ArrayList

I wrote a pretty standard bit of code utilizing String populated ArrayList but when I try running it, I get the following error:

error: size has private access in ArrayList.

The code is as follows:

System.out.println(testedArticles.size);

Upvotes: 9

Views: 29660

Answers (2)

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26094

There is nothing like ArrayList.size. You need to use .size() method.

You need to use

System.out.println(testedArticles.size());

instead of

System.out.println(testedArticles.size);

Upvotes: 5

Richard Tingle
Richard Tingle

Reputation: 17226

You are attempting to access a private member of ArrayList, part of its internal working that are not supposed to be used externally

If you want to get the size of the arraylist you want the method:

arraylist.size()

Why is it like this

This gives the ArrayList class the option to store size in whatever way it wants. Does it just return size, probably, but it could do a number of other things instead. For example it could calculate size lazily, in which it is only calculated if someone asked for it then it stores that value until it becomes invalid (as more objects are added). This would be useful if calculating size was expensive (very unlikely to be the case here), changed often and was called only occasionally.

Upvotes: 17

Related Questions