如果为 null,则全局访问 T[].length 到 return 0

access T[].length to return 0 globally if null

我正在 APDE 上创建一个应用程序。几周前我发现,我可以从 java 执行任何命令,但我必须指定包。

这里是构造函数:

  ColorTabs(int x, int y, int wid, int hei, boolean orientation, int amount, int value, String[] names) {
    this.x=x;
    this.y=y;
    this.objs=new Place[amount];
    for (int i=0; i<amount; i++)
      if (orientation)
        this.objs[i]=new Switch(i*wid, 0, wid, hei, names.length>i?names[i]:str(i));
      else
        this.objs[i]=new Switch(0, i*hei, wid, hei, names.length>i?names[i]:str(i));
    this.wid=orientation?wid*amount:wid;
    this.hei=orientation?hei:hei*amount;
    this.objs[value].pressed=true;
    this.value=value;
  }

这是我尝试创建一个对象:

new ColorTabs(-margin, -margin, resizedPSiz, resizedPSiz,
            true, 16, 0, null);

最后一个元素必须是可选的,但我不想在构造函数中使用它

String... names

我不想创建这个:

, names==null?0:(names.length>i?names[i]:str(i));

names.length 会导致问题,因为您无法指定空数组的长度。 我决定尝试超越一些 class。但我不知道你在哪里可以超越 class T[]。 我想使用某种解决方案:

import java.lang.???;
class someClass extends ???{
  T(){             //I'm not sure if that's the name of constructor
    super.T();
  }
  int length(){
    if (this==null) return 0;
    else return super.length;
  }
}

我试图在 developer.android.com 上的文档中找到该软件包,但没有找到。

所以我试图找到 String[] class 或 T[] class,但不一定是其他类型的可数。

Java 没有可选的方法或构造函数参数或默认值。您可以通过使用 重载 来定义一个新方法来解决这个问题,该方法只使用默认参数调用另一个方法。

// Pass empty array as "names"
ColorTabs(int x, int y, int wid, int hei, boolean orientation, int amount, int value) {
    this(x, y, wid, hei, orientation, amount, value, new String[0]);
}

ColorTabs(int x, int y, int wid, int hei, boolean orientation, int amount, int value, String[] names) {
    ...
}

您当前的方法存在一些问题:

  • 数组 类 是“特殊的”- 您不能扩展它们。
  • 对象永远不会 null - “null”是“此变量不指向对象”的特殊关键字。所以像 this == null 这样的东西将永远是 false 因为 this 总是指向“当前”对象。