while(true)和Collections

Maw*_*wia 1 java collections while-loop

我无法理解这两个代码之间的区别;

public static void main(String[] args) {
    List<String> list = new ArrayList<>();
    while (true) {
      list.add("Hello");
    }
  }
Run Code Online (Sandbox Code Playgroud)

java.lang.OutOfMemoryError 在一秒内抛出,

public static void main(String[] args) {
    List<String> list = new ArrayList<>();
    while (true) {
      list.add("Hello");
      System.out.println(list.size());  // Simply display the size of List
    }
  }
Run Code Online (Sandbox Code Playgroud)

使用值为20767725的list.size()java.lang.OutOfMemoryError 在5分钟后抛出.

Jon*_*eet 8

简单地说 - 显示2000万行文本需要相当长的时间.

很容易证明这一点.运行此代码:

for (int x = 0; x < 20767725; x++) {
    System.out.println(x);
}
Run Code Online (Sandbox Code Playgroud)

我怀疑这也需要大约5分钟.