一 打印list中的元素
0 JAVA风格的最简做法import java.util.List;
...
List<Integer> l = new ArrayList(3);
System.out.println(l);
1 JAVA风格的做法
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
...
List<Integer> l = new ArrayList(3);
System.out.println(Arrays.toString(l.toArray()));
2 类似C++的用法
List<Integer> l = new ArrayList(3);
for (int i = 0; i < l.size(); ++i) {
System.out.println(l.get(i));
}
3 for each 的方法
List<Integer> l = pt.getRow(4);
for (Integer i: l) {
System.out.println(i);
}
二. 打印一维数组
1 JAVA风格的做法
int [] aa = new int [] {1, 2, 3, 4, 5};
System.out.println(aa.toString()); //[I@103c520 注意这个写法是错误的,打印出来的是垃圾值。
System.out.println(Arrays.toString(aa)); //[1, 2, 3, 4, 5]
2 类似 C++的for循环
for (int i = 0; i < aa.length; ++i) {
System.out.println(aa[i]);
}
for (int i: aa) {
System.out.println(i);
}
三. 使用itertator的方法(用到InnerClass)
public class DataStructure {
// Create an array
private final static int SIZE = 15;
private int[] arrayOfInts = new int[SIZE];
public DataStructure() {
// fill the array with ascending integer values
for (int i = 0; i < SIZE; i++) {
arrayOfInts[i] = i;
}
}
public void printEven() {
// Print out values of even indices of the array
DataStructureIterator iterator = this.new EvenIterator();
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
System.out.println();
}
interface DataStructureIterator extends java.util.Iterator<Integer> { }
// Inner class implements the DataStructureIterator interface,
// which extends the Iterator<Integer> interface
private class EvenIterator implements DataStructureIterator {
// Start stepping through the array from the beginning
private int nextIndex = 0;
public boolean hasNext() {
// Check if the current element is the last in the array
return (nextIndex <= SIZE - 1);
}
public Integer next() {
// Record a value of an even index of the array
Integer retValue = Integer.valueOf(arrayOfInts[nextIndex]);
// Get the next even element
nextIndex += 2;
return retValue;
}
}
public static void main(String s[]) {
// Fill the array with integer values and print out only
// values of even indices
DataStructure ds = new DataStructure();
ds.printEven();
}
}
The output is:0 2 4 6 8 10 12 14
四. 打印二维数组
public class FFChap7 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int [][] numArray = new int [5][5];
for (int i = 0; i < 5;++i) {
for (int j = 0; j < 5;++j) {
numArray[i][j]++;
}
}
System.out.println(Arrays.deepToString(numArray));
}
}
五. 打印Arraylist
ArrayList alist = new ArrayList(5);
alist.add(10);
alist.add(11);
alist.add(12);
alist.add(13);
System.out.println(alist);
参考资料:
https://docs.oracle.cm/javase/tutorial/java/javaOO/innerclasses.html