Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Create an array with letter characters as index

Is it possible to create in Java an array indexed by letter characters ('a' to 'z') rather than by integers?

With such an array "a", I would like to useit in this way, for example

print (a['a']);
like image 244
zell Avatar asked Jun 17 '12 07:06

zell


2 Answers

Is it possible to create in Java an array indexed by letter characters ('a' to 'z') rather than by integers?

Of course it is possible.
You could do this either like this:

char theChar = 'x';  
print (a[theChar - 'a']);   

or assuming handling only ASCII strings just declare the array of size 256. The directly index the array using your character.

char[] a = new char[256];   
char theChar = 'x';  
print (a[theChar]);    

Now you don't care if it is uppercase/lower case or whatever.
Actually if you are interested specifically for ASCII strings using a Map could be overkill compared to a simple array. The array doesn't waste so much space and perhaps a Map (a very efficient construct) is too much for such a simple task.

like image 194
Cratylus Avatar answered Oct 06 '22 00:10

Cratylus


Yes and no. Yes because you can do it and it will compile. Try the following code:

class foo {
    public static void main(String[] args) throws Exception {
        int a[] = new int[100];
        a['a'] = '1';
        System.out.printf("%d\n", a['a']);
    }
}

No, because the chars will be implicitly converted to ints, which doesn't sound like what you're looking for.

like image 26
vanza Avatar answered Oct 06 '22 00:10

vanza