Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
I am learning GoF Java Design Patterns and I want to see some real life examples of them. Can you guys point to some good usage of these Design Patterns.(preferably in Java's core libraries). Thank you
What issues / pitfalls must be considered when overriding equals and hashCode?
What is the best way to iterate through a HashMap?
What are the reasons behind the decision to not have a fully generic get method in the interface of java.util.Map<K,V>. To clarify the question, the signature of the method is V get(Object key) instead of V get(K key) and I'm wondering why (same thing for remove, containsKey, containsValue).
What is the best way to convert a Map<key,value> to a List<value>? Just iterate over all values and insert them in a list or am I overlooking something?
If I have the value "foo", and a HashMap<String> ftw for which ftw.containsValue("foo") returns true, how can I get the corresponding key? Do I have to loop through the hashmap? What is the best way to do that?
What is null? Is null an instance of anything? What set does null belong to? How is it represented in the memory?
Does MATLAB have any support for hash tables? Some background I am working on a problem in Matlab that requires a scale-space representation of an image. To do this I create a 2-D Gaussian filter with variance sigma*s^k for k in some range., and then I use each one in turn to filter the image. Now, I want some sort of mapping from k to the filtered image. If k were always an integer, I'd ...
Apart from the fact that hashSet does not allow duplicate values, what is the difference between a HashMap and Hashset...? I mean implementaion wise.....? It's a little bit vague because both use hash table to store values.....
I have always thought that the .equals() method in java should be overridden to be made specific to the class you have created. In other words to look for equivalence of two different instances rather than two references to the same instance. However I have encountered other programmers who seem to think that the default object behavior should be left alone and a new method created for testing ...
I'm looking for a light weight java library for dealing with RDF data. It needs to be able to parse and write RDF xml data. Also I would like it to support simple querying of an RDF model. SPARQL would be nice but not required and I don't need an inferencing capabilities. I've used Jena, but it's not very light weight.
This is the ability to run your application on a cluster of servers with the intent to distribute the load and also provide additional redundancy. I've seen a presentation for GridGain and I was very impressed with it. Know of any others?
I'm researching and experimenting more with Groovy and I'm trying to wrap my mind around the pros and cons of implementing things in Groovy that I can't/don't do in Java. Dynamic programming is still just a concept to me since I've been deeply steeped static and strongly typed languages. Groovy gives me the ability to duck-type, but I can't really see the value. How is duck-typing more pro...
Looking at the source of Java 6, HashSet<E> is actually implemented using HashMap<E,Object>, using dummy object instance on every entry of the Set. I think that wastes 4 byte (on 32-bit machines) for the size of the entry itself. But, why is it still used? Is there any reason to use it besides making it easier to maintain the codes?
Supposing I have a File f that represents a directory, then f.delete() will only delete the directory if it is empty. I've found a couple of examples online that use File.listFiles() or File.list() to get all the files in the directory and then recursively traverses the directory structure and delete all the files. However, since it's possible to create infinitely recursive directory structur...
What is the difference between the following maps I create (in another question, people answered using them seemingly interchangeably and I'm wondering if/how they are different): HashMap<String, Object> map = new HashMap<String, Object>(); Map<String, Object> map = new HashMap<String, Object>();
How to move a particular HashMap entry to Last position? For Example, I have HashMap values like this: HashMap<String,Integer> map = new HashMap<String,Integer>(); map= {Not-Specified 1, test 2, testtest 3}; "Not-Specified" may come in any position. it may come first or in the middle of the map. But i want to move the "Not-Specified" to the last position. How can I do that? th...
I was wandering if there is a class out there that implements both Map and List interfaces in Java. I have a data structure that is primarily a Map. I map strings (IDs) to Images. But in a specific part of my code i need to present the user with all the available IDed Images. The only way to do that so far is to write this : for (String id : myMap.keySet()) { // get the image like this "...
DISCLAIMER: THIS QUESTION WAS NOT MEANT TO BE ARGUMENTATIVE!!!!!!! What is fastest and less memory draining way of searching a key-value pair? I will be storing items in a key-value like relation and I need to access them quickly. Should I use a SQLite database? A Map? A Hashtable? A HashMap? Please give some advantages/disadvantages of using whatever method of searching.
Is there a Java Map keySet() equivalent for C++'s std::map? The Java keySet() method returns "a set view of the keys contained in this map."
If I have a class that needs to implement an interface but one or more of the methods on that interface don't make sense in the context of this particular class, what should I do? For example, lets say I'm implementing an adapter pattern where I want to create a wrapper class that implements java.util.Map by wrapping some immutable object and exposing it's data as key/value pairs. In this cas...
  /*
   * Copyright 1997-2006 Sun Microsystems, Inc.  All Rights Reserved.
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   *
   * This code is free software; you can redistribute it and/or modify it
   * under the terms of the GNU General Public License version 2 only, as
   * published by the Free Software Foundation.  Sun designates this
   * particular file as subject to the "Classpath" exception as provided
   * by Sun in the LICENSE file that accompanied this code.
  *
  * This code is distributed in the hope that it will be useful, but WITHOUT
  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  * version 2 for more details (a copy is included in the LICENSE file that
  * accompanied this code).
  *
  * You should have received a copy of the GNU General Public License version
  * 2 along with this work; if not, write to the Free Software Foundation,
  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  *
  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  * CA 95054 USA or visit www.sun.com if you need additional information or
  * have any questions.
  */
 
 package java.util;

An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.

This interface takes the place of the Dictionary class, which was a totally abstract class rather than an interface.

The Map interface provides three collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings. The order of a map is defined as the order in which the iterators on the map's collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do not.

Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map. A special case of this prohibition is that it is not permissible for a map to contain itself as a key. While it is permissible for a map to contain itself as a value, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a map.

All general-purpose map implementation classes should provide two "standard" constructors: a void (no arguments) constructor which creates an empty map, and a constructor with a single argument of type Map, which creates a new map with the same key-value mappings as its argument. In effect, the latter constructor allows the user to copy any map, producing an equivalent map of the desired class. There is no way to enforce this recommendation (as interfaces cannot contain constructors) but all of the general-purpose map implementations in the JDK comply.

The "destructive" methods contained in this interface, that is, the methods that modify the map on which they operate, are specified to throw UnsupportedOperationException if this map does not support the operation. If this is the case, these methods may, but are not required to, throw an UnsupportedOperationException if the invocation would have no effect on the map. For example, invoking the putAll(java.util.Map) method on an unmodifiable map may, but is not required to, throw the exception if the map whose mappings are to be "superimposed" is empty.

Some map implementations have restrictions on the keys and values they may contain. For example, some implementations prohibit null keys and values, and some have restrictions on the types of their keys. Attempting to insert an ineligible key or value throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible key or value may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible key or value whose completion would not result in the insertion of an ineligible element into the map may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface.

This interface is a member of the Java Collections Framework.

Many methods in Collections Framework interfaces are defined in terms of the equals method. For example, the specification for the containsKey(Object key) method says: "returns true if and only if this map contains a mapping for a key k such that (key==null ? k==null : key.equals(k))." This specification should not be construed to imply that invoking Map.containsKey with a non-null argument key will cause key.equals(k) to be invoked for any key k. Implementations are free to implement optimizations whereby the equals invocation is avoided, for example, by first comparing the hash codes of the two keys. (The java.lang.Object.hashCode() specification guarantees that two objects with unequal hash codes cannot be equal.) More generally, implementations of the various Collections Framework interfaces are free to take advantage of the specified behavior of underlying java.lang.Object methods wherever the implementor deems it appropriate.

Parameters:
<K> the type of keys maintained by this map
<V> the type of mapped values
Author(s):
Josh Bloch
Since:
1.2
See also:
HashMap
TreeMap
Hashtable
SortedMap
Collection
Set
public interface Map<K,V> {
    // Query Operations

    
Returns the number of key-value mappings in this map. If the map contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.

Returns:
the number of key-value mappings in this map
    int size();

    
Returns true if this map contains no key-value mappings.

Returns:
true if this map contains no key-value mappings
    boolean isEmpty();

    
Returns true if this map contains a mapping for the specified key. More formally, returns true if and only if this map contains a mapping for a key k such that (key==null ? k==null : key.equals(k)). (There can be at most one such mapping.)

Parameters:
key key whose presence in this map is to be tested
Returns:
true if this map contains a mapping for the specified key
Throws:
java.lang.ClassCastException if the key is of an inappropriate type for this map (optional)
java.lang.NullPointerException if the specified key is null and this map does not permit null keys (optional)
    boolean containsKey(Object key);

    
Returns true if this map maps one or more keys to the specified value. More formally, returns true if and only if this map contains at least one mapping to a value v such that (value==null ? v==null : value.equals(v)). This operation will probably require time linear in the map size for most implementations of the Map interface.

Parameters:
value value whose presence in this map is to be tested
Returns:
true if this map maps one or more keys to the specified value
Throws:
java.lang.ClassCastException if the value is of an inappropriate type for this map (optional)
java.lang.NullPointerException if the specified value is null and this map does not permit null values (optional)
    boolean containsValue(Object value);

    
Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

More formally, if this map contains a mapping from a key k to a value v such that (key==null ? k==null : key.equals(k)), then this method returns v; otherwise it returns null. (There can be at most one such mapping.)

If this map permits null values, then a return value of null does not necessarily indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the key to null. The containsKey operation may be used to distinguish these two cases.

Parameters:
key the key whose associated value is to be returned
Returns:
the value to which the specified key is mapped, or null if this map contains no mapping for the key
Throws:
java.lang.ClassCastException if the key is of an inappropriate type for this map (optional)
java.lang.NullPointerException if the specified key is null and this map does not permit null keys (optional)
    V get(Object key);
    // Modification Operations

    
Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)

Parameters:
key key with which the specified value is to be associated
value value to be associated with the specified key
Returns:
the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key, if the implementation supports null values.)
Throws:
java.lang.UnsupportedOperationException if the put operation is not supported by this map
java.lang.ClassCastException if the class of the specified key or value prevents it from being stored in this map
java.lang.NullPointerException if the specified key or value is null and this map does not permit null keys or values
java.lang.IllegalArgumentException if some property of the specified key or value prevents it from being stored in this map
    V put(K key, V value);

    
Removes the mapping for a key from this map if it is present (optional operation). More formally, if this map contains a mapping from key k to value v such that (key==null ? k==null : key.equals(k)), that mapping is removed. (The map can contain at most one such mapping.)

Returns the value to which this map previously associated the key, or null if the map contained no mapping for the key.

If this map permits null values, then a return value of null does not necessarily indicate that the map contained no mapping for the key; it's also possible that the map explicitly mapped the key to null.

The map will not contain a mapping for the specified key once the call returns.

Parameters:
key key whose mapping is to be removed from the map
Returns:
the previous value associated with key, or null if there was no mapping for key.
Throws:
java.lang.UnsupportedOperationException if the remove operation is not supported by this map
java.lang.ClassCastException if the key is of an inappropriate type for this map (optional)
java.lang.NullPointerException if the specified key is null and this map does not permit null keys (optional)
    V remove(Object key);
    // Bulk Operations

    
Copies all of the mappings from the specified map to this map (optional operation). The effect of this call is equivalent to that of calling put(k, v) on this map once for each mapping from key k to value v in the specified map. The behavior of this operation is undefined if the specified map is modified while the operation is in progress.

Parameters:
m mappings to be stored in this map
Throws:
java.lang.UnsupportedOperationException if the putAll operation is not supported by this map
java.lang.ClassCastException if the class of a key or value in the specified map prevents it from being stored in this map
java.lang.NullPointerException if the specified map is null, or if this map does not permit null keys or values, and the specified map contains null keys or values
java.lang.IllegalArgumentException if some property of a key or value in the specified map prevents it from being stored in this map
    void putAll(Map<? extends K, ? extends V> m);

    
Removes all of the mappings from this map (optional operation). The map will be empty after this call returns.

Throws:
java.lang.UnsupportedOperationException if the clear operation is not supported by this map
    void clear();
    // Views

    
Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.

Returns:
a set view of the keys contained in this map
    Set<K> keySet();

    
Returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. If the map is modified while an iteration over the collection is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The collection supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Collection.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.

Returns:
a collection view of the values contained in this map
    Collection<V> values();

    
Returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.

Returns:
a set view of the mappings contained in this map
    Set<Map.Entry<K, V>> entrySet();

    
A map entry (key-value pair). The Map.entrySet method returns a collection-view of the map, whose elements are of this class. The only way to obtain a reference to a map entry is from the iterator of this collection-view. These Map.Entry objects are valid only for the duration of the iteration; more formally, the behavior of a map entry is undefined if the backing map has been modified after the entry was returned by the iterator, except through the setValue operation on the map entry.

Since:
1.2
See also:
Map.entrySet()
    interface Entry<K,V> {
        
Returns the key corresponding to this entry.

Returns:
the key corresponding to this entry
Throws:
java.lang.IllegalStateException implementations may, but are not required to, throw this exception if the entry has been removed from the backing map.
        K getKey();

        
Returns the value corresponding to this entry. If the mapping has been removed from the backing map (by the iterator's remove operation), the results of this call are undefined.

Returns:
the value corresponding to this entry
Throws:
java.lang.IllegalStateException implementations may, but are not required to, throw this exception if the entry has been removed from the backing map.
        V getValue();

        
Replaces the value corresponding to this entry with the specified value (optional operation). (Writes through to the map.) The behavior of this call is undefined if the mapping has already been removed from the map (by the iterator's remove operation).

Parameters:
value new value to be stored in this entry
Returns:
old value corresponding to the entry
Throws:
java.lang.UnsupportedOperationException if the put operation is not supported by the backing map
java.lang.ClassCastException if the class of the specified value prevents it from being stored in the backing map
java.lang.NullPointerException if the backing map does not permit null values, and the specified value is null
java.lang.IllegalArgumentException if some property of this value prevents it from being stored in the backing map
java.lang.IllegalStateException implementations may, but are not required to, throw this exception if the entry has been removed from the backing map.
        V setValue(V value);

        
Compares the specified object with this entry for equality. Returns true if the given object is also a map entry and the two entries represent the same mapping. More formally, two entries e1 and e2 represent the same mapping if
     (e1.getKey()==null ?
      e2.getKey()==null : e1.getKey().equals(e2.getKey()))  &&
     (e1.getValue()==null ?
      e2.getValue()==null : e1.getValue().equals(e2.getValue()))
 
This ensures that the equals method works properly across different implementations of the Map.Entry interface.

Parameters:
o object to be compared for equality with this map entry
Returns:
true if the specified object is equal to this map entry
        boolean equals(Object o);

        
Returns the hash code value for this map entry. The hash code of a map entry e is defined to be:
     (e.getKey()==null   ? 0 : e.getKey().hashCode()) ^
     (e.getValue()==null ? 0 : e.getValue().hashCode())
 
This ensures that e1.equals(e2) implies that e1.hashCode()==e2.hashCode() for any two Entries e1 and e2, as required by the general contract of Object.hashCode.

        int hashCode();
    }
    // Comparison and hashing

    
Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings. More formally, two maps m1 and m2 represent the same mappings if m1.entrySet().equals(m2.entrySet()). This ensures that the equals method works properly across different implementations of the Map interface.

Parameters:
o object to be compared for equality with this map
Returns:
true if the specified object is equal to this map
    boolean equals(Object o);

    
Returns the hash code value for this map. The hash code of a map is defined to be the sum of the hash codes of each entry in the map's entrySet() view. This ensures that m1.equals(m2) implies that m1.hashCode()==m2.hashCode() for any two maps m1 and m2, as required by the general contract of java.lang.Object.hashCode().

    int hashCode();
New to GrepCode? Check out our FAQ X