访问 T[].length 以在 null 时全局返回 0



我正在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 会导致问题,因为您无法指定空数组的长度。 我决定尝试取消一些类。但我不知道在哪里可以删除类 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[] 类或 T[] 类,但不一定是其他类型的可数。

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将始终指向"当前"对象。

最新更新