java – 将对象作为参数传递,并在方法内进行修改

前端之家收集整理的这篇文章主要介绍了java – 将对象作为参数传递,并在方法内进行修改前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
假设我有一个Map< String,String>我想删除所有包含foo的值.在优化/内存等方面,最好的方法是什么?下面的四个syso打印相同的结果,也就是说{n2 = bar}.
public static void main(String[] args) {

    Map<String,String> in = new HashMap<String,String>();
    in.put("n1","foo");
    in.put("n2","bar");
    in.put("n3","foobar");

    // 1- create a new object with the returned Map
    Map<String,String> in1 = new HashMap<String,String>(in);
    Map<String,String> out1 = methodThatReturns(in1);
    System.out.println(out1);

    // 2- overwrite the initial Map with the returned one 
    Map<String,String> in2 = new HashMap<String,String>(in);
    in2 = methodThatReturns(in2);
    System.out.println(in2);

    // 3- use the clear/putAll methods
    Map<String,String> in3 = new HashMap<String,String>(in);
    methodThatClearsAndReadds(in3);
    System.out.println(in3);

    // 4- use an iterator to remove elements
    Map<String,String> in4 = new HashMap<String,String>(in);
    methodThatRemoves(in4);
    System.out.println(in4);

}

public static Map<String,String> methodThatReturns(Map<String,String> in) {
    Map<String,String> out = new HashMap<String,String>();
    for(Entry<String,String> entry : in.entrySet()) {
        if(!entry.getValue().contains("foo")) {
            out.put(entry.getKey(),entry.getValue());
        }
    }
    return out;
}

public static void methodThatClearsAndReadds(Map<String,entry.getValue());
        }
    }
    in.clear();
    in.putAll(out);
}

public static void methodThatRemoves(Map<String,String> in) {
    for(Iterator<Entry<String,String>> it = in.entrySet().iterator(); it.hasNext();) {
        if(it.next().getValue().contains("foo")) {
            it.remove();
        }
    }
}

解决方法

最好的方法是methodThatRemoves因为:

>在内存消耗方面:它不会创建一个新的地图,所以不会增加内存开销.>在cpu使用方面:iterator具有O(1)复杂度,用于调用next或删除当前元素.

原文链接:https://www.f2er.com/java/123093.html

猜你在找的Java相关文章