我正在阅读documentation 。对我来说,所有 get
方法都有两个参数,这看起来不太直观。例如。
abstract String get(String key, String def)
Returns the value associated with the specified key in this preference node.
这没有意义。为什么我们需要第二个参数?
我知道当我们为第二个参数提供一个值时,该值将被分配,除非它为空。所以好的一个目的是初始化一个键值
对。但我也可以使用 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
。
关于java - "GET"方法第二个参数的用途是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38176193/