• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Arrays Doubt

 
aslika bahini
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi There,

I have a doubt in the following code.
In the line #1 animal[0]= new Cat(); throws an ArraysStoreException.
Can any of you please explain?




Thanks in Advance
Saritha
 
Ankit Garg
Sheriff
Posts: 9528
33
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's because Dog and Cat are siblings. You cannot add an instance of Cat into an array of Dogs.

Now you will say that the array is of Animals. But actually only the reference is an Animal array. Actually the array itself is a Dog array. Consider this code

Dog dogArr = new Dog[5];
Animal[] arr = dogArr;
arr[0]=new Cat();//ArrayStoreException
Dog dog = godArr[0];//1

Now if there was no ArrayStoreException at the line indicated, then there would be a abnormal situation at line 1. So an array can only store objects of the actual array type. You can read my blog for a detailed article. The link is in my signature...
 
chander shivdasani
Ranch Hand
Posts: 206
Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is a Classic example to why Generics came into existence
 
Mohammad Khan
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
// Following code might help to understand the issue


abstract class Animal {}

class Dog extends Animal {}

class Cat extends Animal {}

class Cow extends Animal {}

public class MyApp {

public static void main(String[] args) {
Animal[] animals = { new Dog(), new Cat(), new Cow() };
Dog[] dogs = { new Dog(), new Dog(), new Dog(), new Dog() };

MyApp app = new MyApp();

try {
app.doStuff(animals);
app.doStuff(dogs);
} catch (AnimalException e) {
System.out.println("Raised exception while trying to store NOT-A Dog in Dog[]");
}
}

public void doStuff(Animal[] animals) throws AnimalException {
if (animals instanceof Dog[]) {
animals[0] = new Dog();
} else {
throw new AnimalException();
}
}
}

class AnimalException extends Exception {}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic