java - why does this code output "0"? -
package algorithms; import cs1.keyboard; import java.util.*; public class sieveoferatosthenes2 { public static void main (string[] args){ //input number , create array length of (num-1) int num = keyboard.readint(); arraylist prime = new arraylist(num); //populate array numbers 2 num for(int = 0; < prime.size()-1; i++) { integer temp = new integer(i+2); prime.add(i, temp); } system.out.println(prime.size());
the constructor here doesn't set size of arraylist num
, sets capacity num
:
arraylist prime = new arraylist(num);
the size of arraylist still zero, loop body never runs. try instead:
for (int = 0; < num - 1; i++) { integer temp = new integer(i+2); prime.add(temp); }
definition of size:
the number of elements in list.
definition of capacity:
each arraylist instance has capacity. capacity size of array used store elements in list. @ least large list size. elements added arraylist, capacity grows automatically. details of growth policy not specified beyond fact adding element has constant amortized time cost.
Comments
Post a Comment