Search code examples
javaarraylistprivate

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);

Solution

  • 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.