Phoenix
Phoenix

Reputation: 8923

When will I get an arraystoreexception and a classcastexception with respect to generics?

My understanding is that you get an ArrayStoreException when you try to insert an object of incompatible type.

Object[] array = new String[1];
array[0] = 1; 

Can someone explain, with an example, when will I get an ArrayStoreException and when will I get a ClassCastException ?

Upvotes: 0

Views: 544

Answers (2)

Parker Berg
Parker Berg

Reputation: 41

A ClassCastException is casting to a wrong subclass, refer to Java 1.6 API for all exception and class information.

This is an example taken from the API:

 Object x = new Integer(0);
 System.out.println((String)x);

Upvotes: 2

thatidiotguy
thatidiotguy

Reputation: 8991

A ClassCastException would happen if you did something like this:

public void stupidMethod(Object o)
{
    //Classcast if o is not a String
    String s = (String)o;

    //do more stupid things
}

An arraystoreexception is similar:

public void stupidMethod()
{
    Object[] array = new String[2];
    //whoops arraystoreexception
    array[0] = new Integer();
}

You should read the API for these exceptions in the future instead of posting here.

Just google java api (class name) and you shall be rewarded with more information than I am willing to type out.

Upvotes: 0

Related Questions