Java Associative Array

From GM-RKB
Jump to navigation Jump to search

A Java Associative Array is an associative array expressed in the Java programming language.



References

2011

  • http://en.wikipedia.org/wiki/Comparison_of_programming_languages_%28mapping%29#Java
    • In Java associative arrays are implemented as "maps"; they are part of the Java collections framework. Since J2SE 5.0 and the introduction of generics into Java, collections can have a type specified; for example, an associative array mapping strings to strings might be specified as follows:

      Map<String, String> phoneBook = new HashMap<String, String>();
      phoneBook.put("Sally Smart", "555-9999");

      phoneBook.put("John Doe", "555-1212");

      phoneBook.put("J. Random Hacker", "555-1337");

      The get method is used to access a key; for example, the value of the expression phoneBook.get("Sally Smart") is "555-9999".

      This code above uses a hash map to store the associative array, by calling the constructor of the Template:Javadoc:SE class; however, since the code only uses methods common to the interface Template:Javadoc:SE, one could also use a self-balancing binary tree by calling the constructor of the Template:Javadoc:SE class (which implements the subinterface Template:Javadoc:SE), without changing the definition of the phoneBook variable or the rest of the code, or use a number of other underlying data structures that implement the Map interface.

      The hash function in Java, used by HashMap and HashSet, is provided by the method Template:Javadoc:SE. Since every class in Javan inherits from Template:Javadoc:SE, every object has a hash function. A class can override the default implementation of hashCode() to provide a custom hash function based on the properties of the object.

2010

public interface Map<K,V> {
    // Basic operations
    V put(K key, V value);
    V get(Object key);
    V remove(Object key);
    boolean containsKey(Object key);
    boolean containsValue(Object value);
    int size();
    boolean isEmpty();

    // Bulk operations
    void putAll(Map<? extends K, ? extends V> m);
    void clear();

    // Collection Views
    public Set<K> keySet();
    public Collection<V> values();
    public Set<Map.Entry<K,V>> entrySet();

    // Interface for entrySet elements
    public interface Entry {
        K getKey();
        V getValue();
        V setValue(V value);
    }
}

The Java platform contains three general-purpose Map implementations: