2D array in Java indexed by characters

If I am mistaken, it is legal to have an array in Java indexed by character values, as they are equivalent to 8-bit numbers. However, the following code generates error messages for me:

int[][] myArray = new int[256][256]; myArray['%']['^'] = 25; 

Is there any way to make this work?

edit : Wow, I really didn't copy the code very well.

0
source share
4 answers

This is not illegal, because in Java (and other languages) char in this case will be passed to int. For example, (int)'%'

Something like this would be safer if you don't know what type of char value it will be.

 int[][] myArray = new int[Character.MAX_VALUE][Character.MAX_VALUE]; myArray['%']['^'] = 24; 

It will work as Java translates this:

 myArray[37][94] = 24; 

Make sure you put the maximum value from char (as already done), which is basically '?' which corresponds to 65535. Or you get an ArrayOutOfBoundsException .

If you know your range, you can still use 256. Just make sure you do the correct bounds checks, where the input is> = 0 and <256.

 public int getItem(int x, int y) { if ((x < 0 && x > 255) || (y < 0 && y > 255)) { return -1; // Or you can throw an exception such as InvalidParameterException } return myArray[x, y]; } 

Checking the boundaries of errors plays an important role for this.

I would rethink what you are trying to do, something like this is unreadable, what are you trying to achieve? Perhaps you can use different collections ?

EDIT

Types changed since you changed the code.

+2
source

The characters are equivalent to an unsigned 16-bit integer, but this is a really terrible design flaw in Java and should not be abused. It is understood that the char type denotes a character, not some integer value that appears to be mapped to a character (or even to a part of a character in the case of surrogate pairs).

The map interface should be used to map something. Arrays should be used only when the index type is a fully-functional integer type, which means its use as such. And when these indices do not fit into a fixed interval, so you do not know the size of the array in advance, it is better to use a map to display integers, rather than resizing the array each time.

Also consider memory usage. For 8-bit characters (ASCII), you can leave with 256x256x4 = 256K bytes of memory. But you are killing the very possibility of internationalizing your statement in a way that is a serious crime. To support the entire 16-bit range, you need 64Kx64Kx4 = 16G bytes! And you still won’t have full support for characters outside this range, but again you won’t have it with Map, this is a Java error, not yours. This is not what many need it anyway.

+1
source

This works (I mean it compiles):

 int[][] myArray = new int[256][256]; myArray['%']['^'] = 10; 

Errors:

  • you have different names for arrays: first myArray and the second table
  • myArray is an array of int arrays, but you assigned a row to a cell.
0
source

All Articles