Java 大小在 ArrayList 中具有私有访问权限

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19450846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 17:17:22  来源:igfitidea点击:

Size has private access in ArrayList

javaarraylistprivate

提问by eggHunter

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

我使用填充的字符串编写了一段非常标准的代码,ArrayList但是当我尝试运行它时,出现以下错误:

error: size has private access in ArrayList.

error: size has private access in ArrayList.

The code is as follows:

代码如下:

System.out.println(testedArticles.size);

采纳答案by Richard Tingle

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

您正试图访问 的私有成员ArrayList,其内部工作的一部分不应在外部使用

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

如果你想获得你想要的方法的数组列表的大小:

arraylist.size()

Why is it like this

为什么会这样

This gives the ArrayListclass 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.

这使ArrayList类可以选择以任何方式存储大小。它是否只是 return size,可能,但它可以做许多其他事情。例如,它可以懒惰地计算大小,其中只有在有人要求时才计算它,然后它会存储该值,直到它变得无效(随着更多对象的添加)。如果计算大小很昂贵(这里不太可能是这种情况),经常更改并且只是偶尔调用,这将很有用。

回答by Prabhakaran Ramaswamy

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

没有什么像 ArrayList.size.你需要使用.size()方法。

You need to use

你需要使用

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

instead of

代替

System.out.println(testedArticles.size);