开发者

Problem with HashMap values()

I make tile memory game. I want when activity start to init tiles with pictures. I try do this:

private void initTiles() {
    // Store name of resources in array
    String[] pictures = new String[] {"tile_circle", "tile_deny", "tile_heart"
                     , "tile_mail", "tile_music", "tile_pin", "tile_splash", "tile_yes"};
    Random rand = new Random();

    int i = 1;

    while(i <= 16) {
        String pic = pictures[rand.nextInt(8)];
        LinkedList<String> list = new LinkedList<String>();

        list = (LinkedList<String>) tilesMapping.values();

         //Check if this picture is already loaded twice
        if(list.indexOf(pic) == -1) {
            ti开发者_StackOverflowlesMapping.put(Integer.valueOf(i), pic);
            i++;
        } else if(list.lastIndexOf(pic) == -1) {
            tilesMapping.put(Integer.valueOf(i), pic);
            i++;
        } else if(list.indexOf(pic) == list.lastIndexOf(pic)) {
            tilesMapping.put(Integer.valueOf(i), pic);
            i++;
        }

    }
}

But when I start game I receive force close. But when comment this row list = (LinkedList<String>) tilesMapping.values(); The game starts.


values() returns a Collection, it does not need to be a LinkedList, so perhaps a ClassCastException happens. You can obtain a linked list by using a copy-constructor:

List list = new LinkedList(map.values()); // or ArrayList`


The fact that the code

LinkedList<String> list = new LinkedList<String>();
list = (LinkedList<String>) tilesMapping.values();

is inside your foreach loop doesn't look right me. I guess it should be above to loop.

Also, you probably didn't mean to create a new LinkedList() and then immediately throw it away, by setting the only reference to that object to the result of tilesMapping.values()... which (presumably) contains one you prepared earlier, yes?

Which brings us to the real problem: What is tilesMapping.values(), and specifically what type does it return? You can't just make something that is NOT really a LinkedList into a linked-list of strings just by type casting it. You can fool the compiler, but it still won't work at runtime.

Cheers. Keith.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜