映射不接受子类

时间:2012-01-27 14:11:04

标签: java map hashmap subclass

我构建了一个map并尝试将给定类的子类放入其中。问题是地图接受其中一些,但不是全部。请让我知道是什么问题,为什么不接受某些子类以及如何解决它。我也尝试让Cat和Dog类延伸Rodent(因为Hamster在这里工作),但这不起作用。谢谢

以下是每个类的代码:

package typeinfo.pets;

public class Pet extends Individual {
  public Pet(String name) { super(name); }
  public Pet() { super(); }
} ///:~

package typeinfo.pets;

public class Rodent extends Pet {
  public Rodent(String name) { super(name); }
  public Rodent() { super(); }
} ///:~

package typeinfo.pets;

public class Cat extends Pet {
  public Cat(String name) { super(name); }
  public Cat() { super(); }
} ///:~

package typeinfo.pets;

public class Hamster extends Rodent {
  public Hamster(String name) { super(name); }
  public Hamster() { super(); }
} ///:~

import typeinfo.pets.*;

import java.util.*;

import static net.mindview.util.Print.*;



public class PetMap {

  public static void main(String[] args) {

    Map<String,Pet> petMap = new HashMap<String,Pet>();

    petMap.put("My Hamster", new Hamster("Bosco"));

    //the two lines here cause problems "Map<String, Pet> is not 
    // applicable to <String, Cat>
    petMap.put("My Cat", new Cat("Molly"));

    petMap.put("My Dog", new Dog("Ginger"));

    print(petMap);

    Pet dog = petMap.get("My Dog");

    print(dog);

    print(petMap.containsKey("My Dog"));

    print(petMap.containsValue(dog));

  }

}

1 个答案:

答案 0 :(得分:1)

正如大多数用户所建议的那样,你的问题并不在于继承树,而是在你导入的类和从哪里开始的。

您在main方法中使用的CatDog可能不是Pet的子类;可能这就是Hamster被接受而其他人不被接受的原因。我试图让你的代码运行并添加了缺少的代码。例如,以下内容有效:

import java.util.*;

class Individual {
    public String name;
    public Individual(String name) {
        this.name = name;
    }
    public Individual () {
        this.name = new String();
    }
}
class Pet extends Individual {
  public Pet(String name) { super(name); }
  public Pet() { super(); }
} ///:~

class Rodent extends Pet {
  public Rodent(String name) { super(name); }
  public Rodent() { super(); }
} ///:~

class Cat extends Pet {
  public Cat(String name) { super(name); }
  public Cat() { super(); }
} ///:~

class Dog extends Pet {
      public Dog(String name) { super(name); }
      public Dog() { super(); }
    } ///:~

class Hamster extends Rodent {
  public Hamster(String name) { super(name); }
  public Hamster() { super(); }
} ///:~



public class PetMap {

  public static void main(String[] args) {

    Map<String,Pet> petMap = new HashMap<String,Pet>();

    petMap.put("My Hamster", new Hamster("Bosco"));

    // the two lines now work
    petMap.put("My Cat", new Cat("Molly"));

    petMap.put("My Dog", new Dog("Ginger"));

    System.out.println(petMap);

    Pet dog = petMap.get("My Dog");

    System.out.println(dog);

    System.out.println(petMap.containsKey("My Dog"));

    System.out.println(petMap.containsValue(dog));

  }

}

请重新检查您的包装定义和进口。