Search code examples
javakeyvaluepair

How to store key value pairs in Java without using HashMap or any other collection?


I want to be able to associate values to some keys without using collections. I am aware of HashMaps, but I am trying to explore a more basic way to do it.

For example, if I was to count the frequency of each word in a file, I would take words as keys and frequency as values.

Some languages allow accessing arrays using values as well . For example, Lua.

I also want to be able to access every key with its value.


Solution

  • Have two arrays of equal size

    String [] keys = new String [5];
    String [] values = new String [5];
    
    keys [0] = "name";
    values [0] = "Fred";
    
    String getValue (String key) {
    
       // loop around keys array to get index of key
    
       return values [index];
    }