Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

java - 在HashMap中使用接口作为值(Using an interface as a Value in a HashMap)

I've got an interface for a housing system as follows:

(我有一个用于住房系统的接口,如下所示:)

public interface ITenant {
    public TenantType getType();
    public String toString();
}

TenantType() just returns the type of tenant, from Tenant class.

(TenantType()仅从Tenant类返回租户的类型。)

The declaration of the HashMap in the House class is as follows:

(在House类中HashMap的声明如下:)

private Map<Room, ITenant> rooms = null;

"rooms" is used to check if a room contains a TenantType, if it does, it's occupied.

(“房间”用于检查房间是否包含TenantType,如果包含,则表明该房间已被占用。)

    public int getAvailableRooms() {
    int numOfFreeRooms = 0;
    for (int i=0; i<numberOfRooms; i++) {
        if (rooms.get(i) == null ) {
            numOfFreeRooms += 1;
        }
    }
    return numOfFreeRooms;
}

This method returns how many rooms are free, by using the HashMap.

(此方法通过使用HashMap返回多少个空闲房间。)

I believe I understand how interfaces work, but not how they work with HashMaps.

(我相信我了解接口如何工作,但不了解它们如何与HashMaps一起工作。)

  ask by Toby translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...