Nidhish Puthiyadath
Nidhish Puthiyadath

Reputation: 119

NullPointerException when using putAll(map) to put map into properties

I am trying to put a map into a properties using putAll() and get a NullPointerException even when my map is not null

Map<String,Object> map = item.getProperties();
Properties props = new Properties();
if(map!=null) {
    props.putAll(map);  //NPE here
}

The item.getProperties() returns Map<String,Object> and I want to store those properties into a properties file.

I also tried to instantiate the map first

Map<String,Object> map = new HashMap<String, Object>()
map = item.getProperties();
Properties props = new Properties();
if(map!=null) {
    props.putAll(map);  //NPE here
}

I know that the map is not null, since I can see the map values in the log.

Upvotes: 3

Views: 11907

Answers (2)

Project_B_J
Project_B_J

Reputation: 59

 public synchronized V put(K key, V value) {
// Make sure the value is not null
if (value == null) {
    throw new NullPointerException();
}

// Makes sure the key is not already in the hashtable.
Entry tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
    if ((e.hash == hash) && e.key.equals(key)) {
    V old = e.value;
    e.value = value;
    return old;
    }
}

modCount++;
if (count >= threshold) {
    // Rehash the table if the threshold is exceeded
    rehash();

        tab = table;
        index = (hash & 0x7FFFFFFF) % tab.length;
}

// Creates the new entry.
Entry<K,V> e = tab[index];
tab[index] = new Entry<K,V>(hash, key, value, e);
count++;
return null;
}

Maybe your map has null key or value.

Upvotes: 0

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280141

The Properties class extends Hashtable which does not accept null values for its entries.

Any non-null object can be used as a key or as a value.

If you try to put a null value, the Hashtable#put(Object, Object) method throws a NullPointerException. It's possible your

map = item.getProperties();

contains null values.

Upvotes: 6

Related Questions