Garrett Outlaw
Garrett Outlaw

Reputation: 225

Lookup Tables in Java?

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?

Upvotes: 6

Views: 43672

Answers (4)

stanimirsp
stanimirsp

Reputation: 3106

I know it has been a long time since you asked the question and I'm sure you did your assignment successfully. However, I'm sharing my answer with everyone who, like me is wondering what a lookup table is.

Lookup table it's just an array.

Lookup table (Array) it's extremely fast in delivering the data we need O(1). Imagine it's like a two-column table. In the first column are keys/indexes and in the second are values/data. We can directly access that data we need by index.

Upvotes: 1

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

Upvotes: 2

jlordo
jlordo

Reputation: 37843

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

Upvotes: 10

christopher
christopher

Reputation: 27356

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

Upvotes: 3

Related Questions