[英]Printing the objects in the array
我不确定如何打印数组中的对象。 打印(); 方法是从不同的类文件调用的。 有人能告诉我我是正确使用 .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();
}
}
}
您的代码尝试重新实现现有集合的行为。 使用ArrayList<Place>
或LinkedList<Place>
代替。 在网络上浏览大量示例
这将帮助您轻松地将Place
转换为可读字符串, 请看这里
如果您仍想打印出一个数组,请使用ArrayUtils.toString(storage)
。 但是您还需要实现toString()
:
public class Place {
@Override
public String toString() {
return String.format("<PUT YOU FORMAT HERE>");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.