首页 > 解决方案 > 对象列表 Java 任务

问题描述

我已经获得了以下主要方法,并且必须为 ObjectList 类编写代码。我应该推断 ObjectList 类的必要功能并自己编写该类,但是我不确定我需要做什么才能实现此功能。非常感谢任何帮助理解这一点。这是给我的代码:

   ObjectList ol = new ObjectList(3);

   String s = "Im Happy";
   Dog d = new Dog();
   DVD v = new DVD();
   Integer i = 1234;

   System.out.println(ol.add(s));
   System.out.println(ol.add(d));
   System.out.println(ol.add(v));
   System.out.println(ol.add(i));

   ol.remove(0);
   System.out.println(ol.add(i));


   System.out.println("Is the list full? "+ isFull()); 
   System.out.println("Is the list empty? "+ isEmpty());

   System.out.println("Total number of objects in the list: " + getTotal());

   Object g = ol.getObject(1);
   g.bark();

标签: java

解决方案


这很简单,只需要在类中Object使用ArrayListor创建一个类型列表并实现如下功能LinkedListObjectList

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()函数。

此外,当使用 get 函数获取对象时getObject(),您需要在使用该函数之前将其转换为正确的类型。在您的代码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;
}
}

推荐阅读