简体   繁体   English

如何使用HashMap模拟缓存

[英]How can I simulate cache using HashMap

I want to calculate unique characters in a given string and cache them using collections, so that if the string is already present it won't calculate again. 我想计算给定字符串中的唯一字符,并使用集合对其进行缓存,这样,如果该字符串已经存在,就不会再次计算。 For this I have used HashMap , I have made the String as key and it's count as value. 为此,我使用了HashMap ,将String作为键,并将其计为值。 I have written the following code, but it won't add those key-value pairs in the map. 我已经编写了以下代码,但不会在地图中添加这些键值对。 How to resolve this problem? 如何解决这个问题?

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");
    }
}

The maintainCache creates a new local variable map each time its called. 每次调用maintainCache都会创建一个新的局部变量map If you want that map to retain its values between calls, you should extract it out of the method and keep it as a member. 如果希望该映射在调用之间保留其值,则应将其从方法中提取出来并保留为成员。

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;
        }
    }

}

The problem is that HashMap is created newly everytime maintainCache is called. 问题在于,每次调用maintainCache时都会重新创建HashMap。 Please have the map as an property of UniqueCharacters class instead of local variable under method maintainCache 请将该地图作为UniqueCharacters类的属性,而不是方法maintainCache下的局部变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM