Question: How do you create a custom HashMap class, extending HashMap, that can be manipulated like normal?
让我解释一下。根据this question ,您可以通过扩展 ArrayList 然后编写您的方法来使用 ArrayLists 创建自定义方法。我如何使用 HashMap 做到这一点?
我想创建一个可以用 UserList users = new HashMap<Users, Integer>
初始化的 UserList 类.到目前为止,这是我的 UserList 类(class):
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;
}
}
但是每当我输入 private UserList listOfUsers = new HashMap<Users, Integer>;
在主类中,它引发了不兼容的类型错误。我该如何解决?我记得以前学过这个,但后来忘记了。
谢谢
最佳答案
UserList users = new UserList()
,不需要其他任何东西。
通过扩展 HashMap
,您已经告诉编译器 UserList
是一个 HashMap
。
作为建议,您可能希望考虑将组合作为替代设计:Composition over inharitance
关于java - 通过扩展自定义 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57175553/