java—为什么在将子类输入为其父类定义的树Map时出错?

e0bqpujr  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(280)

**结案。**此问题不可复制或由打字错误引起。它目前不接受答案。
**想改进这个问题吗?**更新问题,使其成为堆栈溢出的主题。

26天前关门了。
改进这个问题
在我的程序中,我有一个抽象类telephoneentry,其中包含一个telephonenumber(它实现了comparable)和一个addres,然后我有扩展telephoneentry类的子类person和company。

abstract class TelephoneEntry {
    protected TelephoneNumber number;
    protected String address;

    public abstract void description();

    public TelephoneNumber getNumber() {
        return number;
    }

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

class Person extends TelephoneEntry {
    protected String name;
    protected String surname;

    public Person(String name, String surname, String address, int code, long number) {
        this.name = name;
        this.surname = surname;
        this.address = address;
        this.number = new TelephoneNumber(code, number);
    }

    @Override
    public void description() {
        System.out.println("Name: " + name);
        System.out.println("Surname: " + surname);
        System.out.println("Address: " + address);
        System.out.println("TelephoneNumber: " + number.toString());
        }
    }

class Company extends TelephoneEntry {
    protected String name;

    public Company(String name, String address, int code, long number) {
        this.name = name;
        this.address = address;
        this.number = new TelephoneNumber(code, number);
    }

    @Override
    public void description() {
        System.out.println("Name: " + name);
        System.out.println("Address: " + address);
        System.out.println("TelephoneNumber: " + number.toString());
    }
}

public class TelephoneNumber implements Comparable<TelephoneNumber> {
    private int countryCode;
    private long localNumber;

    public TelephoneNumber(int code, long number) {
        countryCode = code;
        localNumber = number;
    }

    @Override
    public int compareTo(TelephoneNumber otherNumber) {
        if (Integer.compare(getCountryCode(), otherNumber.getCountryCode()) != 0) {
        return Long.compare(getLocalNumber(), otherNumber.getLocalNumber());
    } else
        return Integer.compare(getCountryCode(), otherNumber.getCountryCode());

    }

    public String toString() {
        String out = "";
        out += ("+" + countryCode + " " + localNumber);
        return out;
    }
}

但是当我尝试将它们传递给树Map时

TreeMap<TelephoneNumber,  TelephoneEntry> map = new TreeMap<>();

我得到一个错误说明:

"The method add(TelephoneNumber, Person) is undefined for the type TreeMap<TelephoneNumber,TelephoneEntry>"
"The method add(TelephoneNumber, Company) is undefined for the type TreeMap<TelephoneNumber,TelephoneEntry>"

我不确定这个错误的原因是什么,因为它们都继承了telephoneentity使用的密钥。

hm2xizp9

hm2xizp91#

Map有 put() 方法,而不是 add() 方法,用于添加条目。
将代码更改为:

myMap.put(myTelephoneNumber, myTelephoneEntry);

相关问题