我正在尝试实现个人的abstractMap。我的项目中有2种类型的地图,一种<String , List<Box>>
和一种<String , Box>
(方框是一个用其数量包裹物品的类)。但是,当我尝试map的put方法时,它向我显示“ UnsupportedOperationException-如果此地图不支持put操作”
这是地图的抽象类
public abstract class TamagotchiMap<X> extends AbstractMap<String, X> {
@Override
public abstract Set<Entry<String, X>> entrySet();
public abstract void attachCategories(Set<String> categories);
public abstract void addItemForCategory(String category, Box box);
public abstract String getCategory(Box box);
public Collection<String> getAllCategories() {
return this.keySet();
}
}
有2个类扩展了该类
1)
public class InventoryMainMap extends TamagotchiMap<Box> {
private final Set<Entry<String, Box>> entry = new HashSet<>();
@Override
public Set<Entry<String, Box>> entrySet() {
return entry;
}
@Override
public void attachCategories(final Set<String> categories) {
for (String category: categories) {
this.put(category, null);
}
}
/**
*
* @return main item for this category
* @param category is the category of item
*/
public Box getMainItem(final String category) {
return this.get(category);
}
@Override
public String getCategory(final Box box) {
for (String category: this.getAllCategories()) {
if (this.get(category).containsItem(box.getItem())) {
return category;
}
}
return null;
}
@Override
public void addItemForCategory(final String category, final Box box) {
if (this.containsKey(category)) {
this.replace(category, box);
}
}
}
2)
public class ItemContainerMap extends TamagotchiMap<List<Box>> {
private final Set<Entry<String, List<Box>>> entry = new HashSet<>();
@Override
public Set<Entry<String, List<Box>>> entrySet() {
return entry;
}
@Override
public String getCategory(final Box box) {
for (String category: this.getAllCategories()) {
for (Box boxIterator: this.get(category)) {
if (boxIterator.containsItem(box.getItem())) {
return category;
}
}
}
return null;
}
@Override
public void addItemForCategory(final String category, final Box box) {
if (this.containsKey(category)) {
if (!this.get(category).contains(box)) {
System.out.println("nuovo item");
this.get(category).add(box);
} else {
System.out.println("item esistente");
this.get(category).stream().filter(iterBox -> iterBox.equals(box)).forEach(iterBox -> iterBox.increaseQuantity());
}
} else {
throw new NoSuchElementException();
}
}
@Override
public void attachCategories(final Set<String> categories) {
for (String category: categories) {
this.put(category, new LinkedList<Box>());
}
}
}
当我做
class Test {
TamagotchiMap map = new ItemContainerMap();
map.put(string, box);
}
它使我看到了我已经说过的异常。
好像看跌期权无法使用,您知道我错了吗?
最佳答案
从UnsupportedOperationException
继承的put(K, V)
的默认实现是抛出AbstractMap
。您可以自己实现它,也可以让您的TamagotchiMap
扩展一个具体的Map
类,例如HashMap
而不是AbstractMap
。