Lookup Tables in Java?

爷,独闯天下 提交于 2019-12-30 09:44:04

问题


In my Computer Science course, we're learning about Lookup Tables. But our teacher did not provide any examples in the lesson pages he has posted, nor the videos he provided. All he did was tell us what it was but he wants us to use them in our next assignment. But he has failed to give us examples of how to do it. We were learning about Arrays before we got into Lookup Tables. Can someone

  1. Tell me what a Lookup Table is? (Lots of details please?)
  2. Provide some examples of a Lookup Table? We're supposed to use Arrays?

回答1:


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



回答2:


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".




回答3:


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".


来源:https://stackoverflow.com/questions/15114335/lookup-tables-in-java

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