Anonymous Array Creation

18 January 2012 By Nithya Vasudevan 460 views No Comment
2 Flares Twitter 0 Facebook 2 Google+ 0 2 Flares ×

This is the third method for declaring, creating and initializing an array object in one line.

One Dimensional Array

Person[] arr;
arr = new Person[] {p1, p2};

or,

Person[] arr = new Person[] {p1, p2}; 

When you use this method size should not be specified.
Person[] arr = new Person[2] {p1, p2}; //ERROR

This method is useful when we want to create a just-in-time array to use as an argument to a method that takes an array parameter.
Example,

package com.ibytecode.arrays;
class Person
{
	String name;
	public Person(String name) {
		this.name = name;
	}
}
public class ArrayMethod3 {
	public static void main(String[] args) {
		Person p1 = new Person("Kumar");
		Person p2 = new Person("Dev");
		method(new Person[] {p1, p2});
	}
	
	public static void method(Person[] array)
	{
		//use Person[] array here			
	}
}

Two Dimensional Array

You can also use this method to create a two dimensional array as shown below.

double[][] studentAvgs = new double[][]{{80.0,90.0}, {75.5, 65.5, 85.5}, {98.0}};

Tags: , , , , ,