-2

i'm having trouble with a type cas error, and i can't find out why it keeps poping...

Error message : [Ljava.lang.Object; cannot be cast to [Lnet.masterthought.cucumber.json.Stuff;

it pops on the line this.stuffs = (Stuff[]) sList.toArray();

Anyone has any idea what's the problem ?

public class Element {
    private Stuff[] stuff;

    //... getters setters

    public function updateStuff(Stuff[] newStuff) {
        Map<String, Stuff> stuffMap = new HashMap<String, Stuff>();
        for (Stuff s : this.stuffs) {
            stuffMap.put(s.getName(), s);
        }

        for (Stuff s : prevStuffs) {
            if (stuffMap.containsKey(s.getName())) {
                stuffMap.get(s.getName()).setValue(s.getValue());
            }
        }
        ArrayList<Stuff> sList = new ArrayList<Stuff>(stuffMap.values());
        this.stuffs = (Stuff[]) sList.toArray();
    }
}
beresfordt
  • 5,088
  • 10
  • 35
  • 43
Xeltor
  • 4,626
  • 3
  • 24
  • 26

1 Answers1

3

sList.toArray(); returns an Object[]. This cannot be a cast to a Stuff[]. You can cast an array to an array of a supertype, but not a subtype.

You can get a Stuff[], but it's a bit awkward.

this.stuffs = new Stuff[sList.size()];
sList.toArray(this.stuffs);

As pointed out in the comments, you can also do this:

this.stuffs = sList.toArray(new Stuff[0]);

If the argument passed to toArray is not big enough, a new array of the same type is allocated and returned.

Paul Boddington
  • 37,127
  • 10
  • 65
  • 116