本文介绍了涵盖继承中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
import java.util.AbstractList;
import java.util.AbstractList;
公共类ItemSet扩展了AbstractList {
public class ItemSet extends AbstractList {
private Item[] arr;
private ItemClass itemClass;
public ItemSet(Item item) {
arr = new Item[1];
arr[0] = item;
}
/*
* (non-Javadoc)
*
* @see java.util.AbstractList#add(java.lang.Object)
*/
@Override
public boolean add(Item e) {
boolean isNotAdded = true;
for (int i = 0; i < arr.length; i++) {
if (e.getRule().compareTo(arr[i].getRule())) {
if (e.getDot() == arr[i].getDot()) {
isNotAdded = false;
break;
}
}
}
if (isNotAdded) {
Item[] oldArr = arr;
arr = new Item[oldArr.length + 1];
System.arraycopy(oldArr, 0, arr, 0, oldArr.length);
arr[oldArr.length] = e;
}
return isNotAdded;
}
@Override
public Item get(int index) {
return arr[index];
}
@Override
public int size() {
return arr.length;
}
// SETTER
/**
* @param itemClass
* the itemClass to set
*/
public void setItemClass(ItemClass itemClass) {
this.itemClass = itemClass;
}
//
// GETTER
/**
* @return the itemClass
*/
public ItemClass getItemClass() {
return itemClass;
}
//
}
如何覆盖例如删除方法?如何不使用自己的列表实现?
How to cover for instance removes methods?How do not use an own list implementation?
推荐答案
如果您不想继承remove(),则不要扩展AbstractList
,而是将想要的方法委托给ArrayList
.
If you don't want to inherit remove(), then don't extend AbstractList
, instead delegate the methods you want to an ArrayList
.
就像这样(出于对上帝的爱,请不要评论您的安装者和吸气者)
Like this (and for the love of god don't comment your setters and getters)
public class ItemSet {
private final ArrayList<Item> items = new ArrayList<Item>();
private ItemClass itemClass;
public ItemSet(Item item) {
items.add(item);
}
public boolean add(Item e) {
boolean isNotAdded = true;
for (Item item : items)
if (e.getRule().compareTo(item.getRule()))
if (e.getDot() == item.getDot()) {
isNotAdded = false;
break;
}
// why are you adding here?
if (isNotAdded)
items.add(e);
return isNotAdded;
}
public Item get(int index) {
return items.get(index);
}
public int size() {
return items.size();
}
public void setItemClass(ItemClass itemClass) {
this.itemClass = itemClass;
}
public ItemClass getItemClass() {
return itemClass;
}
}
}
这篇关于涵盖继承中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!