在另一个方法中调用返回值

时间:2018-04-09 20:32:49

标签: java return-value

我想在另一种方法中使用o的值我该怎么做。我搜索很多但不成功!

public static Object getKeyFromValue(Map hm, Object value) {
    for (Object o : hm.keySet()) {
      if (hm.get(o).equals(value)) {
          System.out.println("find "+o); // like this but when i write it on another method error occor!!!
          
        return o;

1 个答案:

答案 0 :(得分:0)

我建议同时搜索和删除对象,而不是使用两种方法,顺便提一下它的remove()你不应该使用put()。

这是我的方法,你可以看到我也使用Integer / String而不是Object,当你只有String值时,使用超类没有意义。

public static void removeObject(Map<Integer, String> map, String value) {
   for (Map.Entry<Integer, String> entry : map) {
       if (entry.getValue().equals(value) ) {
           map.remove(entry.getKey());
       }
   }
}