我想计算给定字符串中的唯一字符,并使用集合对其进行缓存,这样,如果该字符串已经存在,就不会再次计算。为此,我使用了HashMap
,我将String作为键,并将其计为值。我已经编写了以下代码,但不会在地图中添加这些键值对。如何解决这个问题?
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");
}
}
答案 0 :(得分:1)
col1 colX col2 col3
ch AA NA 3
ch AA NA 4
ch AA NA 5
每次被调用时都会创建一个新的局部变量maintainCache
。如果希望该映射在调用之间保留其值,则应将其从方法中提取出来并保留为成员。
答案 1 :(得分:1)
import java.util.HashMap;
import java.util.Map;
public class StringCacheTest {
public static void main(String[] args) {
StringCache cache = new StringCache();
System.out.println("Unique characters : " + cache.getUniqueCharactersCount("test"));
System.out.println("Unique characters : " + cache.getUniqueCharactersCount("test2"));
System.out.println("Unique characters : " + cache.getUniqueCharactersCount("test"));
}
}
class StringCache {
private Map<String, Long> cache;
public StringCache(){
this.cache = new HashMap<>();
}
public Long getUniqueCharactersCount(String string){
if(string == null){
throw new RuntimeException("Null string");
}
if(cache.containsKey(string)){
System.out.println("String " + string + " found in cache");
return cache.get(string);
} else {
System.out.println("String " + string + " not found in cache");
long uniqueCharactersCount = string
.chars()
.distinct()
.count();
cache.put(string, uniqueCharactersCount);
return uniqueCharactersCount;
}
}
}
答案 2 :(得分:0)
问题在于,每次调用maintainCache时都会重新创建HashMap。请将该地图作为UniqueCharacters类的属性,而不是在maintainCache方法下的局部变量