How to use for loop to call list.size () repeatedly in JAVA
This article introduces how to use the for loop to repeatedly call list.size () in JAVA, the content is very detailed, interested friends can refer to, hope to be helpful to you.
The code is as follows:
Public class Test2 {public static void main (String [] args) {List list = new ArrayList (); list.add ("1"); list.add ("2"); for (int I = 0; I
< list.size(); i++) { System.out.println(i); } }} 这里将list.size()放在了for循环里,按朋友的说法,这里应该会调用多次。 接下来我查看了字节码发现,这里确实会调用多次list.size()方法,字节码如下:
For more information on bytecode instruction parsing, please see: http://www.blogjava.net/DLevin/archive/2011/09/13/358497.html
Then we look at the source code of ArrayList calling the size () method, which directly returns a size variable of type int, and this size variable changes the value of the size every time it is added or deleted.
Conclusion: after enthusiastic discussion and correction by netizens, list.size () will be called many times in the for loop, and the list.size () method will directly return a size global variable declared in the class. Although this size is directly stored in the heap, it does incur the performance overhead of pushing the stack off the stack every time a function call occurs.
On how to use the for loop in JAVA to repeatedly call list.size () to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.