CSC300: More about Arrays [10/12] |
java.util.Arrays includes a useful function for printing arrays:
01 |
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.
Python | Java | ||||
---|---|---|---|---|---|
|
|
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])