简体   繁体   中英

Custom HashMap by extending

Question: How do you create a custom HashMap class, extending HashMap, that can be manipulated like normal?

Let me explain. According to this question , you can create custom methods with ArrayLists by extending ArrayList and then writing your method. How would I do that with HashMaps?

I want to create a UserList class that can be initialized with UserList users = new HashMap<Users, Integer> . This is my class for UserList so far:

public class UserList extends HashMap<Users, Integer> {

    public Users getUser(UUID uuid) {
        for (Users u: keySet()) {
            if (u.getUuid().equals(uuid))
                return u;
        }

        return null;
    }

    public Boolean containsPlayer(UUID uuid) {
        for (Users u: keySet()) {
            if (u.getUuid().equals(uuid))
                return true;
        }

        return false;
    }

    public Users removeUser(UUID uuid) {
        for (Users u: keySet()) {
            if (u.getUuid().equals(uuid)) {
                remove(u);
                return u;
            }
        }

        return null;
    }
}

But whenever I type private UserList listOfUsers = new HashMap<Users, Integer>; in the main class, it brings up an incompatible type error. How do I fix this? I remember learning about this before, but I've since forgotten.

Thanks

UserList users = new UserList() , no need for anything else.

By extending the HashMap you already told the compiler that UserList is a HashMap .

As a suggestion, you may want to consider composition as an alternative design: Composition over inharitance

I know your question is about extending HashMap, but you can achieve the same by encapsulating the HashMap implementation inside your object:

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class UserList  {
    private Map<UUID, Users> users;

    public UserList() {
        this.users = new HashMap<>();
    }

    public Users getUser(UUID uuid) {
        return this.users.getOrDefault(uuid, null);
    }

    public Users removeUser(UUID uuui){
        return this.users.remove(uuui);
    }

    public Boolean containsPlayer(UUID uuid) {
        return this.users.keySet().contains(uuid);
    }

    public Users addUser(UUID uuid, Users users) {
        return this.users.put(uuid, users);
    }
}

class Users{}

class Main{
    public static void main(String[] args) {
        UserList userList = new UserList();
        UUID uuid = UUID.randomUUID();
        Users users = new Users();
        userList.addUser(uuid, users);
        userList.removeUser(uuid);
        userList.containsPlayer(uuid);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM