Char
lookup tableCharacter transformations can be slow. We can have elaborate logic in them. With a lookup table, we can instantly map characters.
For ASCII chars, like ABC, we can use a small lookup table of 128 chars. Then we can use char
values (like "A") as the index, and store chars in each slot.
Let us begin with this simple example. We use a char
table of 128 elements to store the result of toUpperCase
. We store uppercased versions of all chars.
Character.toUpperCase
is needed.public class Program { static char[] table = new char[128]; public static void main(String[] args) { // Set up the lookup table. for (int i = 0; i < 128; i++) { // Get character for this int. char c = (char) i; // Convert to uppercase. char result = Character.toUpperCase(c); // Store in lookup table field. table[c] = result; } // Loop over string characters. String name = "Carrot123"; for (int i = 0; i < name.length(); i++) { // Get char from lookup table based on string char. char result = table[name.charAt(i)]; // Write results. System.out.println(name.charAt(i) + "/" + result); } } }C/C a/A r/R r/R o/O t/T 1/1 2/2 3/3
Character lookup tables are an optimization in many programs. They help the most on slow operations—toUpperCase
is too fast to show much benefit from a table.
For a cipher, like ROT13 or a Caesar cipher, a char
lookup table can show more improvement. And lookup tables (a form of memoization) are excellent for mathematical computations as well.
Char
lookup tables must accommodate all characters, or use a range check for values. This ensures no exceptions are thrown.