Academic Java    Java Tutorial  >  Arrays  >  anonymous arrays

anonymous arrays Example

Java anonymous arrays EXAMPLE output This program draws a red triangle.

It uses two anonymous arrays to define the vertices of the triangle. Notice where and how the two arrays are initialized.

Anonymous arrays are generally only used to save the programmer having to provide names for them.

Using named arrays would have worked equally well.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Anonymous Arrays Example
import java.awt.*;

class AnonymousArraysExample {

   public static void main(String[] args) {

      int w = 200, h = 200;

      APolygon p = new APolygon(
         Color.red, 
         new int[]{0,w/2,-w/2}, 
         new int[]{-h/2,h/2,h/2}
      );
      p.draw();

   }
}

10-14 The vertices of a polygon are defined by two int arrays of offset-coordinates, one for x the other for y.
In this example they are initialized as anonymous arrays, that is they are not assigned to a variable.
The required syntax combines the new operator with braces for initialization.