有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    这里的constructor并没有将ArrayList的大小设置为^{,而是将容量设置为^{

    ArrayList prime = new ArrayList(num);
    

    ArrayList的大小仍然为零,因此循环体永远不会运行。试试这个:

    for (int i = 0; i < num - 1; i++)
    {
        Integer temp = new Integer(i+2);
        prime.add(temp);
    }
    

    size的定义:

    the number of elements in this list.

    能力的定义:

    Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.