Topic: 转帖..看看这道题!

  Print this page

1.转帖..看看这道题! Copy to clipboard
Posted by: aiff
Posted on: 2004-10-14 01:44

看看这道题!

public class CatsAndDogs{
public static void main(String[] args){
try{
ArrayList cats=new ArrayList();
for(int i=0;i<7;i++)
cats.add(new Cat(i));
cats.add(new Dog(2));
for (int i=0;i<cats.size();i++)
{
((Cat)cats.get(i)).print();

}
catch(Exception ex){
System.out.println(ex.getMessage());
}
}
}
前面的两个类cat和dog类,我就不说了
我要说的是为什么第8个元素dog2不能输出,大伙帮我解释一下!

2.Re:转帖..看看这道题! [Re: aiff] Copy to clipboard
Posted by: jsmile
Posted on: 2004-10-14 05:08

Dog is not Cat Sad.
Java won't catch cast exceptions at compile time. It is a RuntimeException. It all depends on coder itself. The compiler goes: if you want to cast and do mean it, fine, I will cast it for you, at your own risk.
That's why JDK 5.0 Generic Types comes along:
ArrayList<Cat> cats = new ArrayList<Cat>();
cats.add(0, new Cat(0));
cats.get(0).print();
If a dog tries to sneak in, it will be caught at compile time.
Try to cast it to Animal, Pet or something else which Dog and Cat both extend or implement. And it makes sense too in real life. Turning a dog into a cat, I don't think so.

3.Re:转帖..看看这道题! [Re: aiff] Copy to clipboard
Posted by: kuyacai
Posted on: 2004-10-14 09:29

jsmile说得有理。在你将dog造型为cat时,系统会抛出异常。

4.Re:转帖..看看这道题! [Re: aiff] Copy to clipboard
Posted by: dorrenchen
Posted on: 2004-10-15 00:40


// to print both cat and dog
  for (int i=0;i<cats.size();i++){
    Object obj = cats.get(i);
    if(obj instanceof Cat){
      ((Cat)obj).print();
    }else if(obj instanceof Dog){
      ((Dog)obj).print();
    }
  }

5.Re:转帖..看看这道题! [Re: aiff] Copy to clipboard
Posted by: yoti
Posted on: 2004-10-15 02:00

jdk5才出来,大家好像都知道有泛型类一样,真是搞得我哭笑不得,偶可还不打算现在就装5


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923