gpt4 book ai didi

java - 如何使用HashMap模拟缓存

转载 作者:行者123 更新时间:2023-12-02 01:55:43 26 4
gpt4 key购买 nike

我想计算给定字符串中的唯一字符并使用集合缓存它们,这样如果字符串已经存在,则不会再次计算。为此,我使用了HashMap,我将字符串作为键,并将其作为值。我编写了以下代码,但它不会在 map 中添加这些键值对。如何解决这个问题?

class UniqueCharacters {

public int uniqueCharacters(String s)
{
List<Character> list=new ArrayList<Character>();
for(int i=0; i<s.length();i++)
{
if(!(list.contains(s.charAt(i))))
{
list.add(s.charAt(i));
}
}
for(Character c:list)
{
System.out.println(c);
}
int count=list.size();
maintainCache(s, count);

System.out.println(count);
return count;
}

public void maintainCache(String s, int count)
{
Map<String,Integer> map=new HashMap<String,Integer>();
for(Map.Entry<String, Integer> entry: map.entrySet())
{
if(entry.getKey().equals(s))
{
System.out.println(entry.getKey()+" "+entry.getValue());
System.out.println("String was already there");
}
else
{
map.put(s, count);
System.out.println("String added to the cache");
}
}
}
}

public class UniqueCharactersTest {

public static void main(String[] args) {
UniqueCharacters u=new UniqueCharacters();
u.uniqueCharacters("hello");
}
}

最佳答案

maintainCache 每次调用时都会创建一个新的局部变量 map。如果您希望该映射在调用之间保留其值,则应该将其从方法中提取出来并将其保留为成员。

关于java - 如何使用HashMap模拟缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52345664/

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