让我们考虑一下,我们创建了一些集合,比方说 map :
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(10,20);
现在在示例中,我们有“map”对象和方法“put”,它们将一对添加到我们的 map 中。 但问题是,折磨我的是我怎么知道“put”方法正在工作,我将在没有代码执行的情况下获得新的记录,即没有运行测试。
最佳答案
如果您查看 Map::put()
您将看到的 API:
Throws:
UnsupportedOperationException
- if the put operation is not supported by this map
ClassCastException
- if the class of the specified key or value prevents it from being stored in this map
NullPointerException
- if the specified key or value is null and this map does not permit null keys or values
IllegalArgumentException
- if some property of the specified key or value prevents it from being stored in this map
和
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.)
因此,使用 try-catch
和返回值可以确保 put
操作成功。
但是,如果您想完全确定,您可以覆盖 Map 实现(在本例中为 HashMap
)并创建您的业务逻辑。
在这种情况下,使用 put
并返回一个 boolean
并且不抛出任何 Exception
(或以您想要的方式处理它们)。
public class MyHashMap<K, V> extends HashMap {
@Override
public Boolean put(Object key, Object value) {
try {
super.put(key, value);
} catch (UnsupportedOperationException | ClassCastException | NullPointerException | IllegalArgumentException e) {
return false; // or do what you want!
}
return true;
}
}
然后使用它!:
Map<Integer, Integer> myMap = new MyHashMap();
// printing result
System.out.println(myMap.put(10,20));
// set result to a variable
boolean result = myMap.put(null,null); // result = true
// or even setting and evaluating
if (myMap.put(10,20)) {
// success action
} else {
// fail action
}
注意:这是一个 java 8 实现
关于java - 我们怎么知道应用了某种方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41738128/