java为什么这段代码输出“0”?
package Algorithms;
import cs1.Keyboard;
import java.util.*;
public class SieveofEratosthenes2 {
public static void main (String[] args){
//input number and create an array with the length of (num-1)
int num = Keyboard.readInt();
ArrayList prime = new ArrayList(num);
//populate array with all numbers from 2 to num
for(int i = 0; i < prime.size()-1; i++)
{
Integer temp = new Integer(i+2);
prime.add(i, temp);
}
System.out.println(prime.size());
# 1 楼答案
这里的constructor并没有将ArrayList的大小设置为^{,而是将容量设置为^{:
ArrayList的大小仍然为零,因此循环体永远不会运行。试试这个:
size的定义:
能力的定义: