Frank W
Frank W

Reputation: 81

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

Upvotes: 3

Views: 198

Answers (2)

developer_hatch
developer_hatch

Reputation: 16224

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);
    }
}

Upvotes: 0

orirab
orirab

Reputation: 3333

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

Upvotes: 3

Related Questions