我正在阅读documentation。在我看来,所有get
方法都有两个参数。例如。
abstract String get(String key, String def)
Returns the value associated with the specified key in this preference node.
这没有道理。为什么我们需要第二个论点?
我知道当我们给第二个参数提供一个值时,该值将被赋值,除非它为null。因此,好的一个目的是初始化一个
key-value
对。但是我也可以使用put
初始化键值对。这是示例代码
preferences.put("testKey", "testValue");
System.out.println(preferences.get("testKey", null)); // returns testValue
System.out.println(preferences.get("testKey", "NOT NULL")); // returns testValue
System.out.println(preferences.get("testKey", "WHATEVER")); // returns testValue
因此,我只是看不到第二个参数的好用。我确定有用途。那么,为什么在“首选项”中有第二个参数?
最佳答案
第二个参数是默认值(用于根本不设置首选项的情况)。没有该参数,您将获得null
的未定义属性。