Lookup Tables in Java?

与世无争的帅哥 提交于 2019-12-01 06:00:40

You can use a map to store key/value pairs and lookup a value by it's key:

Map<Integer, String> map = new HashMap<>();
map.put(1, "Foo");
map.put(2, "Bar");
System.out.println(map.get(1)); // prints Foo

If you're supposed to be using Arrays, it's nice and simple.

int[] numbers = new int[5] // Initialise a new array with 5 "spaces".
for(int x = 0; x < 5; x++)
{
    numbers[x] = x;
    // This will populate the array with 0,1,2,3 and 4.
}

Now to access one of these numbers, you use it's index. ie

int value = numbers[3]; // Will return 3.

So you've access the value in the array by using it's index as the "key".

In my understanding a lookup table is a way to get the "value" with a given "key" it is much faster than iterative searching: ie:

for(int x=0; x < 10; x++){
    if( x == n ) {
        return x;
    }
}

this would have to search (at best) 1/2 of 10 to find the matched value of "n". With a "lookupTable" you go directly to the value you need without iterating by using it's "key".

Say you were looking to find the Java variable type for a given mySql datatype. You could use a Map.

Map<String, String> lookUpTable = new Map<>();
lookUpTable.put( "VARCHAR", "String" );

Then you could find the conversion value for a "VARCHAR" data type in Java, it would be

lookUpTable.get("VARCHAR"); // This would give you "String".
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!