Java 打印阵列中的对象

Java 打印阵列中的对象,java,Java,我不知道如何打印数组中的对象。印刷品();方法是从不同的类文件调用的。有人能告诉我是正确使用.print方法还是正确地从数组中获取对象吗 public class PFArray { private int top; int n; Place[] storage; Place p; class PFArray_Exception extends Exception { } public PFArray(int arraylength)

我不知道如何打印数组中的对象。印刷品();方法是从不同的类文件调用的。有人能告诉我是正确使用.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();
        }
    }
}
公共类PFArray{
私人int top;
int n;
放置[]仓库;
p位;
类PFArray_异常扩展异常{
}
公共PFArray(内部阵列长度){
n=排列长度;
储存=新地点[n];
top=0;
}
公共图书馆{
存储=空;
top=0;
}
公共布尔值为_full(){
如果(顶部!=n){
返回false;
}
返回true;
}
公共整数空间_左(){
int space_left=n-顶部;
返回空间_左;
}
public void add_项(Place p)引发PFArray_异常{
if(top==n){
抛出新的PFArray_异常();
}否则{
存储[顶部]=p;
顶部=顶部+1;
}
}
数组中的公共int位置(位置p)引发PFArray异常{
对于(int i=0;i
使用经验证的解决方案 您的代码尝试重新实现现有集合的行为。改用
ArrayList
LinkedList
。浏览

在'Place'类中实现toString 这将帮助您轻松地将
位置
转换为可读字符串

如果仍要打印阵列,请使用
ArrayUtils.toString(存储)
。但您还需要实现
toString()

public class Place {
 @Override
 public String toString() {
    return String.format("<PUT YOU FORMAT HERE>");
 }
}
公共课堂场所{
@凌驾
公共字符串toString(){
返回字符串。格式(“”);
}
}

您是否正确使用它取决于它必须做什么。无论如何,这是错误的:虽然(p!=null){p.print();}如果p不是null,这将导致一个无限循环,并将使您的应用程序崩溃操作我已经修复了它,函数是打印我存储在数组中的“位置”,我该如何做?不管怎样,我得到了它谢谢