gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-28 23:33:32 25 4
gpt4 key购买 nike

假设我有一个 Map<String, String>我想删除 value 包含的所有条目 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, 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());
}
}
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 因为:

  1. 在内存消耗方面:它不会创建新 map ,因此不会增加内存开销。
  2. 在 CPU 使用方面:迭代器在调用 next 或删除当前元素时具有 O(1) 复杂度。

关于java - 将对象作为参数传递并在方法内对其进行修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10994369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com