How do I create a hash table in Java?

后端 未结 8 760
没有蜡笔的小新
没有蜡笔的小新 2021-02-04 12:41

What is the most straightforward way to create a hash table (or associative array...) in Java? My google-fu has turned up a couple examples, but is there a standard way to do t

相关标签:
8条回答
  • 2021-02-04 13:19

    What Edmund said.

    As for not calling .add all the time, no, not idiomatically. There would be various hacks (storing it in an array and then looping) that you could do if you really wanted to, but I wouldn't recommend it.

    0 讨论(0)
  • 2021-02-04 13:20
    Map map = new HashMap();
    Hashtable ht = new Hashtable();
    

    Both classes can be found from the java.util package. The difference between the 2 is explained in the following jGuru FAQ entry.

    0 讨论(0)
  • 2021-02-04 13:22

    You can use double-braces to set up the data. You still call add, or put, but it's less ugly:

    private static final Hashtable<String,Integer> MYHASH = new Hashtable<String,Integer>() {{
        put("foo",      1);
        put("bar",      256);
        put("data",     3);
        put("moredata", 27);
        put("hello",    32);
        put("world",    65536);
     }};
    
    0 讨论(0)
  • 2021-02-04 13:24
    import java.util.HashMap;
    
    Map map = new HashMap();
    
    0 讨论(0)
  • 2021-02-04 13:30

    It is important to note that Java's hash function is less than optimal. If you want less collisions and almost complete elimination of re-hashing at ~50% capacity, I'd use a Buz Hash algorithm Buz Hash

    The reason Java's hashing algorithm is weak is most evident in how it hashes Strings.

    "a".hash() give you the ASCII representation of "a" - 97, so "b" would be 98. The whole point of hashing is to assign an arbitrary and "as random as possible" number.

    If you need a quick and dirty hash table, by all means, use java.util. If you are looking for something robust that is more scalable, I'd look into implementing your own.

    0 讨论(0)
  • 2021-02-04 13:31
    Hashtable<Object, Double> hashTable = new Hashtable<>();
    

    put values ...

    get max

    Optional<Double> optionalMax = hashTable.values().stream().max(Comparator.naturalOrder());
    
    if (optionalMax.isPresent())
     System.out.println(optionalMax.get());
    
    0 讨论(0)
提交回复
热议问题