gpt4 book ai didi

java - ArrayList 到 HashMap 函数的行为异常

转载 作者:行者123 更新时间:2023-12-01 08:08:05 25 4
gpt4 key购买 nike

所以我正在研究在数组列表中查找两个最常见元素的最佳方法的问题。

我的方法是把整个东西变成一个hashmap,然后看看哪个是最大的。因为我喜欢 HashMap 。他们似乎是一个很好的方法,但我无法想出更好的解决方案。

除了我收到错误之外。这就是你进来的地方 (= !

public static String[] findTwo(ArrayList<String> param) {   
Map<String, Integer> counter = new HashMap<String, Integer>();

for (int i = 0; i < param.size(); i++) {
//param.get(i) is name of inserted object
if (counter.get(i) == null) {
counter.put(param.get(i), 1);
System.out.println(counter.get(i) + "<-- should be 1"); // <-- erroneous part!
} else {
counter.put(param.get(i), counter.get(i)+1);
System.out.println("elsing");
}
System.out.println(counter);
}
return null;
}

此代码打印

null<-- should be 1
{HIHI=1}
null<-- should be 1
{HIHI=1}
null<-- should be 1
{HIHI=1}
null<-- should be 1
{HIHI=1}
null<-- should be 1
{yoyo=1, HIHI=1}
null<-- should be 1
{yoyo=1, HIHI=1}
null<-- should be 1
{yoyo=1, nono=1, HIHI=1}
null<-- should be 1
{yoyo=1, nono=1, froyo=1, HIHI=1}

这是完全错误的!

它说我插入1后值为空。我不知道这是为什么? =(

啊啊谢谢大家!

谁能帮我计算一下时间成本是多少?

最佳答案

counter.get(i) == null应该是counter.get(param.get(i))

事实counter(i)编译是因为 Map#get 收到 Objectiint 自动装箱至Integer (这是一个 Object )。

更好的方法是使用增强的 for在你的 List<String> param 上循环迭代:

for(String parameter : param) {
if (!counter.containsKey(parameter)) {
//logic key is not present...
} else {
//logic when key is present...
}
}

此外,开始面向接口(interface)而不是直接面向类实现的编程。使用ListArrayList 支持:

public static String[] findTwo(List<String> param) {
//...
}

更多信息:

关于java - ArrayList 到 HashMap 函数的行为异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19781729/

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