Create an Array of Nonprimitive Objects

From Java Example Source Code

Jump to: navigation, search

Contents

[edit] Overview - Create an Array of Nonprimitive Objects

This Java example shows how to create an array of non-primitive objects.

[edit] Java Source Code

  • Package: com.bruceeckel
  • File: ArrayClassObj.java
package com.bruceeckel;
 
//: c04:ArrayClassObj.java
//Creating an array of nonprimitive objects.
//From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
//www.BruceEckel.com. See copyright notice in CopyRight.txt.
 
import java.util.Random;
 
public class ArrayClassObj {
    static Random rand = new Random();
 
    public static void main(String[] args) {
	Integer[] a = new Integer[rand.nextInt(20)];
	System.out.println("length of a = " + a.length);
	for (int i = 0; i < a.length; i++) {
	    a[i] = new Integer(rand.nextInt(500));
	    System.out.println("a[" + i + "] = " + a[i]);
	}
    }
}

[edit] What Result You Can Get

Run the program, you will get:


length of a = 10
a[0] = 182
a[1] = 21
a[2] = 130
a[3] = 362
a[4] = 17
a[5] = 359
a[6] = 160
a[7] = 22
a[8] = 221
a[9] = 435

[edit] Required External Library for this Java Example

Need nothing.


[edit] How to Run this Java Example Program

We recommend running this Java example program with Eclipse.

For assistance in working with Eclipse, please see How to Run Java Program with Eclipse.

It's fairly easy.



[edit] Question & Answer

Any question?

Click edit and post your question or answer here.


Personal tools