user3465834
user3465834

Reputation: 1

java - Error casting Set.toArray() as Object[]

I am attempting to grab a random element from a Set of custom Objects (Space) and receiving an error in doing so.

Space[][][][] spaces = new Space[dim][dim][dim][dim];
Set<Space> spaceSet = new HashSet<Space>();

for(int i=0; i<dim; i++)
    for(int j=0; j<dim; j++)
        for(int k=0; k<dim; k++)
            for(int l=0; l<dim; l++) {
                spaces[i][j][k][l] = new Space(i,j,k,l);
                spaceSet.add(spaces[i][j][k][l]);
            }
...
Space s = null;
...

s = (Space[])spaceSet.toArray()[rand.nextInt(spaceSet.size())];  //This line throws the error

Error:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LSpace;
    at Maze.generatePath(Maze.java:45)
    at Maze4D.main(Maze4D.java:15)

Upvotes: 0

Views: 605

Answers (3)

Brian Roach
Brian Roach

Reputation: 76898

Because as the docs point out, toArray() returns an Object[]

You need to use the other toArray(T[] a) if you want the type inferred:

s = spaceSet.toArray(new Space[0])[rand.nextInt(spaceSet.size())];

(The supplied array in this case is just being used for the type inference; toArray() is returning a new Space[] of the appropriate size)

Upvotes: 1

devesh
devesh

Reputation: 106

When trying to work with Random size/space. Its always a better idea to use a map instead of arrays going down several levels. Here is an example of the something similar where you could set/get values with minimal boiler plate code.

import java.util.*;

public class SmartPropertyReader {
    private SmartPropertyReader parent;

    protected final String PRESERVE_MAP = "PRESERVE_MAP";
    protected final String PRESERVE_LIST = "PRESERVE_LIST";
    private String preserveType;

    protected Map<String, SmartPropertyReader> map = new HashMap<String, SmartPropertyReader>();
    protected Object value;
    protected List<SmartPropertyReader> list = new ArrayList<SmartPropertyReader>();

    public SmartPropertyReader(){
        this.parent = null;
    }

    public SmartPropertyReader(SmartPropertyReader parent, String preserveType) {
        this.parent = parent;
        this.preserveType = preserveType;
    }


    public SmartPropertyReader get(String key) {
        SmartPropertyReader subProp = map.get(key);
        if(subProp == null){
            subProp = new SmartPropertyReader(this, PRESERVE_MAP);
            map.put(key, subProp) ;
        }
        return subProp;
    }


    public void setValue(Object passedValue) {
        list.clear();
        map.clear();

        if(passedValue instanceof SmartPropertyReader){
            this.map = ((SmartPropertyReader) passedValue).map;
            this.list = ((SmartPropertyReader) passedValue).list;
        }else{
            this.value = passedValue;
        }

        SmartPropertyReader currPropertyReader = this;
        while(currPropertyReader != null){
            String preserveType = currPropertyReader.preserveType;
            currPropertyReader = currPropertyReader.parent;
            if(PRESERVE_MAP.equals(preserveType)){
                currPropertyReader.clearList();
                currPropertyReader.clearValue();
            }else if(PRESERVE_LIST.equals(preserveType)){
                currPropertyReader.clearValue();
                currPropertyReader.clearMap();
            }
        }
    }

    protected void clearList(){
        list.clear();
    }

    protected void clearMap(){
        map.clear();
    }

    protected void clearValue(){
        this.value = null;
    }

    public Object getValue() {
        if(this.value == null){
            SmartPropertyReader currPropertyReader = parent;
            while(currPropertyReader != null){
                String preserveType = currPropertyReader.preserveType;
                if(PRESERVE_MAP.equals(preserveType)){
                    currPropertyReader.clearMap();
                }else if(PRESERVE_LIST.equals(preserveType)){
                    currPropertyReader.clearList();
                }
                currPropertyReader = currPropertyReader.parent;
            }
        }
        return this.value;
    }


    public SmartPropertyReader get(int index) {
        while(list.size() <= index ){
            list.add(null);
        }
        SmartPropertyReader subProp = list.get(index);
        if(subProp == null){
            subProp = new SmartPropertyReader(this, PRESERVE_LIST);
        }

        list.set(index, subProp);
        return subProp;
    }


    public String toString(){
        String retString = "";
        if(value != null){
            retString = value.toString();
            if(value instanceof String){
                retString = "\"" + retString + "\"";
            }
        }

        if(list.size() > 0){
            String listStr = listString();
            if(!listStr.equals(""))
                retString = "[" + listString() + "]";
        }

        if(map.size() > 0){
            String mapStr = mapString();
            if(!mapStr.equals(""))
                retString = "{" +mapString() + "}";
        }

        return retString;
    }


    private String listString (){
        String str = "";
        boolean first = true;
        for(SmartPropertyReader rblt: list){
            if(rblt != null ){
                String subStr = rblt.toString();
                if(!subStr.equals("")){
                    if(!first)
                        str += ", ";
                    str += subStr;
                    first = false;
                }
            }
        }
        return str;
    }

    private String mapString(){
        String str ="";
        boolean first = true;
        for(String key: map.keySet()){
            SmartPropertyReader rblt = map.get(key);
            if(rblt != null){
                String subStr = rblt.toString();
                if(!subStr.equals("")){
                    if(!first)
                        str += ", ";
                    str += "\""+key + "\": " + subStr;
                    first = false;
                }
            }
        }
        return str;
    }

    public static void main(String[] args) {
        SmartPropertyReader propertyReader = new SmartPropertyReader();
        propertyReader.get("Test").get("2nd key").get("A number value").setValue(10);
        propertyReader.get("Test").get("a key").get(1).get(2).setValue(100);
        propertyReader.get("Test").get("a key").get(1).get(3).setValue(100.345);
        propertyReader.get("Test").get("a key").get(2).get("Nice").setValue("Nice value in the stack");

        propertyReader.get("Test").get("a key").get(5).setValue("This would work too");
        System.out.println(propertyReader.toString());
        System.out.println(propertyReader.get("Test").get("2nd key").get("A number value").getValue());
        System.out.println(propertyReader.get("Test").get("a key").get(1).get(2).getValue());
        System.out.println(propertyReader.get("Test").get("a key").get(1).get(3).getValue());
        System.out.println(propertyReader.get("Test").get("a key").get(2).get("Nice").getValue());
        System.out.println(propertyReader.get("Test").get("a key").get(5).getValue());
    }

}

Upvotes: 0

djechlin
djechlin

Reputation: 60768

An array of Objects cannot be cast to an array of Foos. You will need to iterate over the array and cast each member individually. (Better yet, properly use generics / polymorphism and don't cast.)

Upvotes: 1

Related Questions