CSC300: More about Arrays [10/12] Previous pageContentsNext page

java.util.Arrays includes a useful function for printing arrays:

01
02
03
04
05
06
07
08
09
10
package algs11;
import stdlib.*;
import java.util.Arrays;
public class Hello {
  public static void main (String[] args) {
    double[] lst = { 11, 21, 31 };
    StdOut.println (lst);
    StdOut.println (Arrays.toString(lst));
  }
}

The size of a Java array is fixed when it is created.

PythonJava
01
02
03
04
05
06
07
08
09
10
11
12
13
def createList(size):
    lst = []
    for i in range(size):
        lst.append(0)
    return lst

def main():
    lst = createList(3)
    lst[1] = 21
    print (lst)

 if __name__ == "__main__":
    main()
01
02
03
04
05
06
07
08
09
10
11
12
13
package algs11;
import stdlib.*;
import java.util.Arrays;
public class Hello {
  public static double[] createList (int size) {
    return new double[size];
  }
  public static void main (String[] args) {
    double[] lst = createList(3);
    lst[1] = 21;
    StdOut.println(Arrays.toString(lst));
  }
}

Java arrays are similar to numpy arrays, in that their length is fixed when they are created.

import numpy as np    
a1 = np.array([11, 21, 31]) # fixed length
a2 = np.resize(a1, 4)       # returns a new array of the specified size, with copies of old elements
a2[3] = 41
print (a2)                  # [11, 21, 31, 41]

In addition to numpy arrays, python has another type of arrays, which have variable length like python lists. These are only available for base types, like int and double.

import array as arr    
a3 = arr.array('i', [11, 21, 31]) # variable length array of ints
a3.append (41)
print (a3)                        # array('i', [11, 21, 31, 41])

a4 = arr.array('d', [11, 21, 31]) # variable length array of doubles
a4.append (41)
print (a4)                        # array('d', [11.0, 21.0, 31.0, 41.0])

Previous pageContentsNext page