【问题标题】:Forest f = new Forest(new Tree[]{m,p});? [duplicate]森林 = new Forest(new Treemap});? [复制]
【发布时间】:2018-03-13 07:30:15
【问题描述】:

我是Java初学者,看不懂下面的说法

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

我的理解是我们在森林中构造了一个新的Tree,但下面的表达式{m,p} 我不明白。让我感到困惑的是这些类型的括号{。我以为你总是使用() 作为构造函数。 一个解释会很棒。

PS。

Mango Tree m= new Mango Tree;
Pear Tree p = new PearTree();

【问题讨论】:

  • 在这里,您正在构造一个 Tree 类型的数组,您最初将 mp 放入其中
  • “PS”部分是关于什么的?由于多种原因,它无法编译。
  • 表示后记。

标签: java constructor


【解决方案1】:

new Tree[]{m,p} 创建一个包含两个 Trees 的 Trees 数组 - 由 mp 引用。

相当于:

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

或到:

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

【讨论】:

    【解决方案2】:

    花括号用于初始化数组。

    int[] anArray = {0, 1}
    

    等价于

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

    对于Tree数据类型当然是一样的

    【讨论】:

      猜你喜欢
      • 2012-09-24
      • 2012-12-29
      • 1970-01-01
      • 2021-04-09
      • 1970-01-01
      • 2019-07-19
      • 1970-01-01
      • 2011-06-01
      • 2017-10-27
      相关资源
      最近更新 更多