简体   繁体   中英

ArrayList.contains() return false on equals strings sometimes

I have some trouble with my 'cache' list:

private static List<String> urlsCacheList = new ArrayList<String>();
...
 private static void parseUrlsToQueue(Content content){
        String str = content.toString();
        Pattern p = Pattern.compile(CSS_JS_PATTERN);
        Matcher m = p.matcher(str);
        while (m.find()) {
            String link = m.group();
            if(link.equals("http://static.gazeta.ru/nm2012/css/new_common_css_pda54.css")){
                LOG.warn("******************cache CONTAINS STRING http://static.gazeta.ru/nm2012/css/new_common_css_pda54.css " + urlsCacheList.contains(link) + " ;" + link +";" );
            }

            if(!urlsCacheList.contains(link)){
                urlsCacheList.add(link);
                queue.add(link);
            }
        }
    }

So after some iterations urlsCacheList.contains(link) return false on the equals links, and

LOG.warn("******************cache CONTAINS STRING http://static.gazeta.ru/nm2012/css/new_common_css_pda54.css " + urlsCacheList.contains(link) + " ;" + link +";" );

prints: cache CONTAINS STRING http://static.gazeta.ru/nm2012/css/new_common_css_pda54.css false ;http://static.gazeta.ru/nm2012/css/new_common_css_pda54.css;

But its mostly return true on the same strings, each 30 or 40 iterations its returns false;

UPDATE1: Sorry guys by its seems to me that problem in another place, I call parseUrls() method from Fetcher.class like that:

..
ContentParser.parseUrlsToQueue(content);
..

so after some iterations my urlsCacheList just re-init to null , becaus of own class re-creation;

Can you print the string object hash id's for the strings which fails the contains check. I think it might be because a new String object is created for few Strings and due to this its behaving like this.

One solution is to call String.intern() method to solve this problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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