打印阵列中的对象

时间:2015-06-27 07:57:31

标签: java

我不确定如何打印数组中的对象。 print();方法是从不同的类文件中调用的。有人可以告诉我,我是正确使用.print方法还是正确地从数组中获取对象?

public class PFArray {
    private int top;
    int n;
    Place[] storage;
    Place p;

    class PFArray_Exception extends Exception {
    }

    public PFArray(int arraylength) {
        n = arraylength;
        storage = new Place[n];
        top = 0;
    }

    public void flush() {
        storage = null;
        top = 0;
    }

    public boolean is_full() {
        if (top != n) {
            return false;
        }
        return true;
    }

    public int space_left() {
        int space_left = n - top;
        return space_left;
    }

    public void add_item(Place p) throws PFArray_Exception {
        if (top == n) {
            throw new PFArray_Exception();
        } else {
            storage[top] = p;
            top = top + 1;
        }
    }

    public int position_in_array(Place p) throws PFArray_Exception {
        for (int i = 0; i < top; i++) {
            if (storage[i].equals(p)) {
                return i;
            }
        }
        throw new PFArray_Exception();
    }

    public void remove_item(int n) throws PFArray_Exception {
        if (top != n) {

            top = top - 1;
        } else {
            throw new PFArray_Exception();
        }
    }

    public void unsafe_remove_item(int n) {
        if (top != n) {
            top = top - 1;
        }
    }

    public int unsafe_position_in_array(Place p) {
        for (int i = 0; i < top; i++) {
            if (storage[i].equals(p)) {
                return i;
            }
        }
        return -1;
    }

    public void print_all() {
        System.out.print(n);
        while (p != null) {
            p.print();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

使用经过验证的解决方案

您的代码尝试重新实现现有集合的行为。请改用ArrayList<Place>LinkedList<Place>。浏览numerous examples on the web

在`Place`类

中实现toString

这有助于您轻松将Place转换为可读字符串,look here

如果您仍想要打印出数组,请使用ArrayUtils.toString(storage)。但是您还需要实现toString()

public class Place {
 @Override
 public String toString() {
    return String.format("<PUT YOU FORMAT HERE>");
 }
}