Asha
Asha

Reputation: 11232

Runtime exception during retrieval of object

public static void main(String args[])
{

    List a =new ArrayList<Object>();
    a.add("asha");
    a.add("saha");
    ArrayList<SampleObject> sampleObjects =(ArrayList<SampleObject>)a;//Yes this should not be done but still
    sampleObjects.get(0).getName();// exception is thrown here

}

And the class is

  public class SampleObject implements Serializable
{
    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public String getNumber()
    {
        return number;
    }

    public void setNumber(String number)
    {
        this.number = number;
    }

    private String name;
    private  String number;
}

Can someone please explain why is this runtime exception. How was the data inserted in sampleObjects when the types itself doesnot match?

Upvotes: 1

Views: 65

Answers (2)

Andres
Andres

Reputation: 10725

When you make a cast, you're assuming the responsibility for the object you cast (on this case String) to be of the type you're casting to (on this case SampleObject). Later, at runtime, the JVM discovers you didn't fulfill that responsibility (a String is not a SampleObject) and complains with a RuntimeException (more precisely a ClassCastException).

Upvotes: 2

arkantos
arkantos

Reputation: 567

The exception says you cannot cast String objects to SampleObject type. For a proper retrieval of name properties try this;

SampleObject s1 = new SampleObject();
    s1.setName("asha");
    SampleObject s2 = new SampleObject();
    s1.setName("saha");

    ArrayList<SampleObject> sampleObjects = new ArrayList<>();
    sampleObjects.add(s1);
    sampleObjects.add(s2);

    System.out.println(sampleObjects.get(0).getName());

Upvotes: 0

Related Questions