2 回答

TA貢獻1909條經驗 獲得超7個贊
這是很簡單只需要創建的列表,Object使用類型ArrayList或LinkedList在ObjectList類并實現功能如下
public class ObjectList{
private ArrayList<Object> objects;
public ObjectList(int size)
{
objects = new ArrayList<Object>(size);
}
public String add (Object object)
{
objects.add(object);
//anything you would like to return I'm just returning a string
return "Object Added";
}
public void remove (int index)
{
objects.remove(index);
}
public boolean isEmpty()
{
return objects.isEmpty();
}
public int getTotal()
{
return objects.size();
}
public Object getObject(int index)
{
return objects.get(index);
}
}
在isFull()沒有必要的,因為ArrayList大小可動態變化。您可以使用簡單的數組代替ArrayList然后實現該isFull()函數。
此外,當使用 getgetObject()函數獲取對象時,您需要在使用該函數之前將其轉換為正確的類型。在您的代碼中g.bark()不起作用,因為Object沒有樹皮功能
Object g = ol.getObject(1);
//This can give a runtime error if g is not a Dog
//Use try catch when casting
Dog d = (Dog)g;
d.bark();
編輯
isFull()如果使用數組而不是ArrayList為了簡單起見,請使用該ArrayList版本,這就是您將如何實現和其他功能的方式
public class ObjectList{
private Object[] objects;
private int size = 0;
private int currentIndex = 0;
public ObjectList(int size)
{
this.size = size;
objects = new Object[size];
}
private boolean isFull() {
if(currentIndex == size)
return true;
else
return false;
}
public String add (java.lang.Object object)
{
if ( ! isFull() ) {
objects[currentIndex] = object;
currentIndex++;
return "Object added";
}
return "List full : object not added";
}
public void remove (int index)
{
if( !isEmpty() ) {
//shifting all the object to the left of deleted object 1 index to the left to fill the empty space
for (int i = index; i < size - 1; i++) {
objects[i] = objects[i + 1];
}
currentIndex--;
}
}
public boolean isEmpty()
{
if(currentIndex == 0)
return true;
else
return false;
}
public int getTotal()
{
return currentIndex;
}
public java.lang.Object getObject(int index)
{
if(index < currentIndex)
return objects[index];
else
return null;
}
}

TA貢獻1807條經驗 獲得超9個贊
您似乎想要實現的是“擴展” ArrayList的功能并創建自定義對象列表。您可以做的是創建一個擴展 ArrayList 的類并定義/覆蓋您想要的任何其他方法。
public class ObjectList extends ArrayList<Object> {
//constructor with initial capacity
private int length;
public ObjectList(int size){
super(size);
this.length= size;
}
public Object getObject(int index){
return this.get(index);
}
}
現在您擁有從 ArrayList 類和getObject方法繼承的添加和刪除函數。
關于isFull方法,您可以檢查 ObjectList 類的大小是否等于它被實例化的大小
if(this.size() == this.length){
return true
}
return false;
并獲得總計
public int getTotal(){
return this.size();
}
添加回答
舉報