-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
  • 52,115
  • 13
  • 74
  • 94
Jazzl
  • 17
  • 3

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
  • 374,785
  • 51
  • 663
  • 734
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
  • 511
  • 4
  • 18