使用setProperty()方法遇到的一个小问题

今天调试程序时,在调用Properties类的setProperty(String key, String value)方法时,遇到了一个小问题,程序运行到该语句时抛出异常,提示java.lang.NullPointerException,调查了半天,发现问题出在调用setProperty(String key, String value)时,传递给该方法的value参数的值为null,由于调用setProperty(String key, String value)方法时,它会去调用Hashtable类中的public synchronized Object put(Object key, Object value)方法,查看该方法的源代码实现,代码的开始处就给出了答案:
 1public synchronized Object put(Object key, Object value) {
 2    // Make sure the value is not null

 3    if (value == null{
 4        throw new
 NullPointerException();
 5    }

 6
 7    // Makes sure the key is not already in the hashtable.

 8    Entry tab[] = table;
 9    int hash =
 key.hashCode();
10    int index = (hash & 0x7FFFFFFF%
 tab.length;
11    for (Entry e = tab[index] ; e != null ; e = e.next) 
{
12        if ((e.hash == hash) && e.key.equals(key)) 
{
13        Object old =
 e.value;
14        e.value =
 value;
15        return
 old;
16        }

17    }

18
19    modCount++
;
20    if (count >= threshold) 
{
21        // Rehash the table if the threshold is exceeded

22        rehash();
23

24            tab =
 table;
25            index = (hash & 0x7FFFFFFF%
 tab.length;
26    }
 
27

28    // Creates the new entry.

29    Entry e = new Entry(hash, key, value, tab[index]);
30    tab[index] =
 e;
31    count++
;
32    return null
;
33    }

就此,问题的根源找到了,以后写程序的时候得多注意这些细节。以下附上setProperty(String key, String value)方法的描述:
 1Object java.util.Properties.setProperty(String key, String value)
 2Calls the Hashtable method put. Provided for parallelism with the getProperty method. Enforces use of strings for
 property keys and values. The value returned is the result of the Hashtable call to put. 
 3

 4
See Also:
 5
getProperty

 6
Parameters:
 7key: the key to be placed into this
 property list.
 8
value: the value corresponding to key.

 9
Returns:
10the previous value of the specified key in this property list, or null if
 it did not have one.

11
Since: 1.2
posted @ 2007-07-31 12:27  念月思灵  阅读(834)  评论(0编辑  收藏  举报