views:

85

answers:

5

Hello.

I'm developing an Android application.

I want to set size to a char array like this:

public char[5] language;

But it doesn't work. I have to delete number five to make it work.

I want to limit to five characters to language variable. How can I do that?

Thanks.

+2  A: 

To quote the JLS :

An array's length is not part of its type.

To initialize an array you should do :

public char[] language = new char[5];

Other solutions are

public char[] language = {0, 0, 0, 0, 0};

or

public char[] language;
language = new char[5];

In Java, the array declaration can't contain the size of the array; we only know the variable will contain an array of a specific type. To have an array initialized (and with a size) you have to initialize it either by using new or by using a shortcut which allows to initialize and set values for an array at the same time.

Best way to have to check if an array has a specified size, is actually checking the size of the array yourself with something like if(array.length == 5).


Resources :

On the same topic :

Colin Hebert
+1  A: 
public char[] language = new char[5];

You can't limit the variable itself to length 5; you need to enforce that invariant in your logic. Which means it also shouldn't be public:

private char[] language = new char[5];

...

public void setLanguage(final char[] language)
{
   // or maybe language.length != 5, or whatever you really mean
   if (language.length > 5)
     throw new IllegalArgumentException("language must have length <= 5");
   this.language = language;
}
andersoj
+1  A: 

The variable itself is just of type char-array (char[]), so you can't limit the size of the variable type. What you can limit is the size of the array you instantiate and save to that variable:

char[] language = new char[4];
RonU
Why did you used `4` ?
Colin Hebert
+2  A: 

You cannot do it like that. In Java, the type of an array does not include it's size. See my anwer to this earlier question. (Ignore the part about abstract methods in that question ... it's not the real issue.)

The size of an array is determined by the expression that creates it; e.g. the following creates a char array that contains 5 characters, then later replaces it with another array that contains 21 characters.

public char[] language = new char[5];
...
language = new char[21];

Note that the creation is done is done by the expression on the RHS of the equals. The the length of an array is part of its value, not its type.

Stephen C
A: 

Maybe you want to try the generic style by using ArrayList as the representation of array. So you may find flexibility using ArrayList methods.

private ArrayList<Character> alchar = new ArrayList<Character>(5);

............................................


public void addChar(Character ch){
    if (alchar.size() <= 5)
       alchar.add(ch);
}

public ArrayList<Character> getChars(){
   return alchar;
}
oscarz