; File: MoreFunctions.j ; Author: Carl E. Bredlau ; Purpose: Array functions ; ------------------------------------------------------------------------- .class public MoreFunctions ; ... extends .super java/lang/Object ;---------------------------------------------------- .method public ()V .limit stack 1 aload_0 invokespecial java/lang/Object/()V return .end method ;---------------------------------------------------- ; public static int[] newArray(int size, int value) ; int[] x = new int[size]; ; for (int i = 0; i < size; i++) ; x[i] = value; ; return x; ; .method public static newArray(II)[I ; set limits used by this method .limit locals 4 .limit stack 3 ; Parameters: ; 0 - size ; 1 - value ; 2 - x ; 3 - i ; Stack ; Create array: iload_0 ; size newarray int ; x astore_2 ; ; i = 0 iconst_0 ; 0 istore_3 ; stack is empty for: iload_3 ; i i < size? iload_0 ; size i if_icmpge endfor ; ; x[i] = value; aload_2 ; x iload_3 ; i x iload_1 ; value i x iastore ; iinc 3 1 ; i++ goto for ; stack is empty ; stack is empty endfor: aload_2 areturn ; return the reference to the object .end method ;---------------------------------------------------- ;public static int add(int[] a) ; sum = 0; ; for (i = 0; i < a.length; i++) ; sum += a[i]; ; return sum; .method public static add([I)I .limit locals 3 .limit stack 4 ; Parameters: ; 0 - a (reference) ; Locals: ; 1 - a.length ; 2 - sum ; To be different from the compiler, I'll ; keep a and i on the stack ; and do the comparison at the top of the loop ; It run's a LOT slower ; Stack aload_0 ; a dup ; a a arraylength ; a.length a istore_1 ; a save a.length iconst_0 ; i a i = 0 dup ; 0 i a sum = 0 istore_2 ; i a for: dup ; i i a Is i < length? iload_1 ; length i i a if_icmpge endfor ; ; i a ; sum += a[i] dup2 ; i a i a get a[i] iaload ; a[i] i a iload_2 ; sum a[i] i a iadd ; (sum + a[i]) i a istore_2 ; i a iconst_1 ; 1 i a iadd ; i++ a goto for ; note stack and locals at for and endfor endfor: pop2 ; iload_2 ; sum ireturn .end method