-1

Im a Java beginner and I don't understand the following statement

Forest f = new Forest(new Tree[]{m,p}).

What I understand is that we construct a new Tree inside of a forest but the following expression {m,p} I dont understand. What baffles me are these type of brackets {. I thought that you always used () for a constructor. An explanation would be great.

PS.

Mango Tree m= new Mango Tree;
Pear Tree p = new PearTree();
khelwood
  • 55,782
  • 14
  • 81
  • 108
Jazzl
  • 17
  • 4

2 Answers2

3

new Tree[]{m,p} creates an array of Trees containing two Trees - referenced by m and p.

It is equivalent to:

Tree[] trees = new Tree[2];
trees[0] = m;
trees[1] = p;
Forest f = new Forest(trees);

or to:

Tree[] trees = {m,p};
Forest f = new Forest(trees);
Eran
  • 387,369
  • 54
  • 702
  • 768
1

Curly braces are used to inizialize arrays.

int[] anArray = {0, 1}

is equivalent to

int[] anotherArray = new int[2];
anotherArray[0] = 0;
anotherArray[1] = 1;

Of course is the same for the Tree data type

zuno
  • 563
  • 4
  • 19