Search code examples
javaarraysprocessingprimitive-typesandroid-developer-api

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


I'm creating an app on APDE. few weeks ago I discovered, that I'm able to execute any command from java, but I have to specify the package.

here's constructor:

  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;
  }

here's I try to create an object:

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

last element have to be optional, but I don't want to use this at the constructor

String... names

I don't want to create this:

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

names.length causes problem because you can't specify length of null array. I decided to try to excend some class. but I don't know where you can excend class T[]. I want to use some sort of this solution:

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;
  }
}

I tried to find the package at documentation on developer.android.com, but I didn't found it.

So I'm trying to find the String[] class or T[] class, but not necessarily other types of countables.


Solution

  • Java does not have optional method or constructor parameters or default values. You can get around this by using overloading to define a new method that just calls the other method with a default parameter.

    // 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) {
        ...
    }
    

    Your current approach has a few problems:

    • The array classes are "special" - you cannot extend them.
    • An object is never null - "null" is a special keyword for "this variable does not point to an object". So something like this == null will always be false because this will always point to the "current" object.