Salta al contenuto
Note per Studenti Java - Arrays Report

Java - Arrays

In questa pagina 8

Continues Java - Classes, Objects and ScannerIn Java a class defines instance variables (usually private), a constructor and methods; objects are created with new and used through reference variables. A method call p1.getDistanceFrom(p2) has an implicit argument (the object p1, available inside the method as this) and explicit arguments (p2). Arguments are always passed by value: a copy of the value or of the reference is passed. Comparing references with == tests whether they point to the same object, while equals() compares the content; null is tested with ==; floating point numbers are compared with a tolerance. Public methods are documented with javadoc comments (param, return). The Scanner class splits a string or the standard input into tokens with hasNext() and next() and offers hasNextInt, hasNextDouble, hasNextLine; the end of the standard input is ctrl+z then return on Windows and ctrl+d on Unix. Worked exercises: the MyPoint2D point class with its tester, and the specification of a MyComplex class.Java - Classes, Objects and Scanner → (objects, references, Scanner) and Java - Language BasicsJava (Sun Microsystems, 1991) is an object-oriented language designed to be simple and CPU-independent ("write once, run anywhere"). Every program is made of classes; an executable class needs a main method, and the public class name must match the file name (Hello.java). The source is compiled by javac into bytecode (Hello.class), the machine code of the Java Virtual Machine, which the Java interpreter (java Hello) runs, translating on the fly into real CPU instructions; so Java is both compiled and interpreted, portable at source and bytecode level and of intermediate efficiency. Errors are syntax (found by the compiler) or logical (found only by testing). The grammar has five token types (keywords, identifiers, literals, separators, operators). Complements: loop end tests with less-than, sentinel values and the loop and a half, break and continue, the conditional operator and switch.Java - Language Basics → (loops). Arrays are the Java tool to keep a whole sequence of values in memory (the SumD program of Java - MyComplex, Methods and RedirectionFull MyComplex class (complex numbers): private re and im, constructors chained with this(...) as first statement, methods add, sub, mult, div (= mult by inv), inv, conj, mod, re, im, toString, equalsApprox with a private static helper using a relative tolerance 1E-14. Style rules: give constructor arguments names different from the instance variables (or use this.re = re), never overwrite method arguments, avoid the stray semicolon after if/for/while. Concepts: accessor vs modifier methods (immutable classes only have accessors, e.g. MyComplex and String), boolean methods, formal vs actual arguments, Java passes everything by value (a copy of the number or of the reference), so a method can change the state of an object it receives but cannot make the caller's variable refer to another object; instance methods use this and instance variables, static methods only their explicit arguments; private methods can be called only inside the class. Finally standard input/output redirection with < > >> from the terminal.Java - MyComplex, Methods and Redirection → adds up the numbers it reads but keeps no trace of them).

1. The problem and the tool

Problem. Write a program that

  • reads a sequence of ten floating point numbers from standard input, one per line;
  • asks the user for an integer index and displays the number that occupied that position in the sequence.

All the values must be stored. Ten separate variables chosen by a long sequence of alternatives would work for 10 values, but not if they were a thousand.

The Java tool for storing a sequence of data is the arrayin Java an object that holds a collection of data of the same type placed in sequence (the word means "sequence"); the array structure exists in almost all programming languages.

  • An array in Java is an object that holds a collection of data, all of the same type and placed in sequence.
  • So there are arrays of integers, of floating point numbers, of strings, of bank accounts, and so on.

2. Construction and reference variables

Like any object, an array is built with the new operator, declaring the type of the data it contains; the type is followed by a pair of square brackets holding the length, i.e. the number of elements the array can contain.

java
new double[10];      // creation of an array of 10 double numbers
new BankAccount[10]; // creation of an array of 10
                     // references to BankAccount objects

The element type can be any type valid in Java:

  • one of the primitive types (byte, short, int, long, float, double, char, boolean);
  • a reference to an instance of a class (String, BankAccount, ...).

As for any object, new returns a reference to the newly created object, to be stored in a reference variable of the same type:

java
double[] values = new double[10];

Attention: the square brackets must be present in the definition of the reference variable, but the length must not be indicated: the variable can refer only to arrays of that type, but of any length. Construction and declaration can be done in two steps, and the same variable can later refer to a longer array:

java
// we can do it in two steps
double[] values;
values = new double[10];
...
values = new double[100];

Syntax summary

Purpose Syntax
build an array of length elements of type TypeName new TypeName[length];
define a reference variable for arrays of TypeName TypeName[] referenceName; or TypeName referenceName[];
access an element referenceToArray[index];
  • TypeName is a primitive type or the name of a class.
  • In the declaration the brackets are required and must not contain the length.
  • The elements are initialized with the same rules as instance variables (see below).

3. Using an array

3.1 Initial values

When the array is built, all the elements are initialized following the same rules as instance variables:

  • 0 for numeric variables;
  • false for boolean variables;
  • null for references.

3.2 Access: read and write

The same syntax reads and modifies an element:

java
double[] values = new double[10];
double oneValue = values[3];   // read the element in position 3
values[5] = 3.4;               // modify the element in position 5

3.3 The index

The integer used to access an element is the indexthe integer used to access a particular element of the array. It goes from 0 (included) to the length of the array (excluded), the same convention used for the positions of characters in a string:

  • the first element has index 0;
  • the last element has index length - 1.

The index can in general be any expression with an integer value:

java
double[] values = new double[10];
int a = 4;
values[a + 2] = 3.2; // modifies the 7th element

(index 6 is the 7th element, since counting starts from 0).

3.4 Wrong index

If the index is greater than or equal to the length, or negative, the interpreter throws, at run time, the ArrayIndexOutOfBoundsException exception, which stops the program.

The most common error is using an index equal to the length, the first invalid index:

java
double[] values = new double[10];
values[10] = 2; // RUN TIME ERROR
java
double[] values = new double[10];
for (int i = 0; i <= values.length; i++)   // <= instead of <
{  double k = values[i]; // RUN TIME ERROR
}

Exam rule: a loop over all elements uses i < values.length, never <=.

4. The length of an array

An array is "a somewhat strange object": it has no public methods, neither instance nor static. The only public element is its length, available through the public variable length (attention: it is not a method, no parentheses).

java
double[] values = new double[10];
int a = values.length; // a contains 10

A public instance variable seems to violate encapsulation, but length is declared finala final variable cannot be changed after its value is set, it can only be inspected, so it cannot be changed, only inspected:

java
double[] values = new double[10];
values.length = 15; // COMPILER'S ERROR

According to the slides:

  • this paradigm is in general considered acceptable in object-oriented programming;
  • the alternative would have been a public method giving access to a private variable;
  • the chosen solution is less elegant but gives the same protection of information and is faster in execution.

5. Worked example: SelectValue

It solves the problem of section 1: it reads 10 numbers into an array and prints the one at the position chosen by the user.

java
import java.util.Scanner;
public class SelectValue
{  public static void main(String[] args)
   {  Scanner in = new Scanner(System.in);
      System.out.println("Enter 10 numbers, one per line");

      double[] values = new double[10];
      for (int i = 0; i < values.length; i++){
         if (in.hasNextDouble()) {
            values[i] = in.nextDouble();
         }
      }
      System.out.print("Enter a valid index: ");
      int index = 0;
      if (in.hasNextInt()){
         index = in.nextInt();
      }
      if (index < 0 || index >= values.length){
         System.out.println("Invalid index value");
      }
      else {
         System.out.println("value: " + values[index]);
      }
      in.close();
   }
}

How it works:

6. Initializing the elements

Assigning the elements one by one:

java
int[] primes = new int[3];
primes[0] = 2;
primes[1] = 3;
primes[2] = 5;

If all the elements are known, this syntax is better:

java
int[] primes = {2, 3, 5};

or (acceptable, but less clear):

java
int[] primes = new int[] { 2, 3, 5};

The length is the number of listed values (3 here).

7. Copying an array

7.1 Copying the variable is not copying the array

A variable that refers to an array contains a reference to the array object. Copying the variable to another variable does not copy the array: it produces only another reference to the same array object.

java
double[] x = new double[6];
double[] y = x;

After this, x and y are two names of the same array of 6 elements: changing y[2] changes x[2] too. (Same behaviour seen for objects with == and assignment in Java - Classes, Objects and ScannerIn Java a class defines instance variables (usually private), a constructor and methods; objects are created with new and used through reference variables. A method call p1.getDistanceFrom(p2) has an implicit argument (the object p1, available inside the method as this) and explicit arguments (p2). Arguments are always passed by value: a copy of the value or of the reference is passed. Comparing references with == tests whether they point to the same object, while equals() compares the content; null is tested with ==; floating point numbers are compared with a tolerance. Public methods are documented with javadoc comments (param, return). The Scanner class splits a string or the standard input into tokens with hasNext() and next() and offers hasNextInt, hasNextDouble, hasNextLine; the end of the standard input is ctrl+z then return on Windows and ctrl+d on Unix. Worked exercises: the MyPoint2D point class with its tester, and the specification of a MyComplex class.Java - Classes, Objects and Scanner →.)

7.2 A real copy with a loop

To get a copy of the array:

  1. create a new array of the same type and length;
  2. copy each element of the first array to the corresponding element of the second.
java
double[] val = new double[5];
// below we initialize the array elements
...
double[] otherVal = new double[val.length];
for (int i = 0; i < val.length; i++)
   otherVal[i] = val[i];

7.3 System.arraycopy

Instead of a loop it is possible (and more efficient) to call the static arraycopy() method of the System class (package java.lang). Beware: lower case c in arraycopy.

java
double[] values = new double[10];
// below we initialize the array elements
...
double[] otherValues = new double[values.length];
System.arraycopy(values, 0, otherValues, 0, values.length);

General form:

java
System.arraycopy(from, fromStart, to, toStart, count);
  • from: source array; fromStart: index of its first element to copy;
  • to: destination array; toStart: index where the first copied element goes;
  • count: how many elements are copied.

It allows copying a portion of an array to another array, which must be at least as large as the portion to copy. In the slide's picture, 4 consecutive elements starting at fromStart are copied to 4 consecutive positions starting at toStart.

Exam checklist

  • Array = object with elements of the same type; built with new TypeName[length]; reference variable declared TypeName[] name without the length.
  • Default values: 0 numbers, false booleans, null references.
  • Index from 0 to length - 1; wrong index (negative, or >= length) gives ArrayIndexOutOfBoundsException at run time, not a compile error.
  • length is a public final variable: values.length, never values.length(), and values.length = 15 does not compile.
  • {2, 3, 5} initializes in one line.
  • y = x copies the reference only; copy with a loop on a new array of the same type and length, or with System.arraycopy(from, fromStart, to, toStart, count).

Versione ripasso

Key definitions

Essential code

java
double[] values = new double[10];   // build
double[] v2;                        // declare without length
v2 = new double[100];               // same variable, longer array later
double oneValue = values[3];        // read
values[5] = 3.4;                    // write
int[] primes = {2, 3, 5};           // initialize all at once, length 3
for (int i = 0; i < values.length; i++) { ... }   // strict <
System.arraycopy(values, 0, copy, 0, values.length);   // from, fromStart, to, toStart, count

Worked example: SelectValue

  1. Create double[10], fill it in a loop on values.length with hasNextDouble() and nextDouble().
  2. Read the index with hasNextInt(); if no integer is typed it stays 0.
  3. Check index < 0 || index >= values.length: print "Invalid index value", otherwise print values[index].

Copying

  • New array of the same type and length, then copy each element with a loop, or with System.arraycopy.
  • System.arraycopy copies a portion; the destination must be at least as large as the portion.

Common mistakes

  • Loop with i <= values.length, or values[length]: the first invalid index.
  • values.length() (a method call, wrong) or values.length = 15 (compile error).
  • Thinking y = x copies the array: y[2] changes x[2] too.
  • Expecting an out-of-range index to be a compile error: it fails at run time.

Teoria collegata