今天刚刚开始使用 Java,并且希望实现我正在学习的课程中的 ArrayList。
ArrayList.java
public class ArrayList<T> {
public static final int INITIAL_CAP = 9;
private T[] backingArray;
private int size;
// Constructor
public ArrayList() {
backingArray = (T[]) new Object[INITIAL_CAP];
}
public void addToFront(T data) {
if (data == null) {
throw new java.lang.IllegalArgumentException("ERROR: Cannot add NULL data to the front!");
}
// Shift elements to the right, starting from the last index that has non-null data
for (int i = (this.size - 1); i >= 0; i--) {
this.backingArray[i+1] = this.backingArray[i];
}
// Add new data to the front
this.backingArray[0] = data;
// Increment size
this.size++;
}
public int size() {
return size;
}
public T[] getBackingArray() {
return backingArray;
}
}
Main.java
public class Main {
public static void main(String[] args) {
// Initialize empty arraylist
ArrayList<Integer> arrList = new ArrayList<Integer>();
int sz = arrList.size();
System.out.printf("The size of our ArrayList before adding is: %d\n", sz);
// Add an item to the front of the ArrayList
arrList.addToFront(3);
// Add another item to the front
arrList.addToFront(8);
// Print arrList's size after adding two elements
sz = arrList.size();
System.out.printf("The size of our ArrayList after adding is: %d", sz);
// Print out each element
Object[] arr = arrList.getBackingArray();
for (Object obj: arr) {
System.out.println(obj);
}
}
}
当我按原样编译并运行它时,我收到:
The size of our ArrayList before adding is: 0
The size of our ArrayList after adding is: 28
3
null
null
null
null
null
null
null
当我在第二个
System.out.printf()
语句中添加结束行时,它是 System.out.printf("The size of our ArrayList after adding is: %d\n", sz);
中的 Main.java
我收到正确的输出:
The size of our ArrayList before adding is: 0
The size of our ArrayList after adding is: 2
8
3
null
null
null
null
null
null
null
这是什么行为?
这是因为
System.out.printf()
默认不打印换行符。这类似于 System.out.print()
(无 f)。 System.out.println()
确实将光标移动到下一行,由 ln
后缀表示。这就是为什么在 \n
调用中将 printf
添加到打印语句可以修复您的输出。