简体   繁体   中英

Why does my ArrayList item get converted to an object in Java?

I am trying to get an element from my ArrayList by it's position. I keep getting an error message saying " Object cannot be converted to a string " on the line that gets the ArrayList element.

Here is my code:

ArrayList resources = new ArrayList();

resources.add("Brick");
resources.add("Brick");
resources.add("Brick");
resources.add("Wool");
resources.add("Wool");
resources.add("Wool");
resources.add("Wool");
resources.add("Lumber");
resources.add("Lumber");
resources.add("Lumber");
resources.add("Lumber");
resources.add("Stone");
resources.add("Stone");
resources.add("Stone");
resources.add("Wheat");
resources.add("Wheat");
resources.add("Wheat");
resources.add("Wheat");
resources.add("Wasteland");

long seed = System.nanoTime();
Collections.shuffle(resources, new Random(seed));

for(int i = 0; i < resources.size(); i++){
    String randomResource = resources.get(i);
}

You declared resources to be of type ArrayList , which is a raw type, so resources.get(i) returns an instance of type Object , which cannot be assigned to a String variable.

In order for resources.get(i) to return a String , change its type to ArrayList<String> .

You should use generics for proper type resolving:

ArrayList<String> resources = new ArrayList<String>();

in you code you've created a list of Object.

Also you can put class cast into resource.get line,

String randomResource = (String)resources.get(i);

but in this case you can get ClassCastException in runtime if someone passed different object into your list.

For example:

ArrayList resources = new ArrayList();
resources.add(1); <-- this is also allowed because Integer is instance of Object

for(int i = 0; i < resources.size(); i++){
        String randomResource = (String)resources.get(i); <-- ClassCastException because Integer isn't instance of String 

    }

More information about generics in java: Java Generics FAQs

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