java编程思想-第五章-某些练习题

时间:2023-03-08 15:11:53
java编程思想-第五章-某些练习题

参考https://blog.csdn.net/caroline_wendy/article/details/46844651

10&11

finalize()被调用的条件

Java1.6以下的条件:

(1)类未被调用(置null)(2)调用System.gc()

1.8的条件:

(1)调用System.gc().(在调用了System.gc()之后,finalize()才被执行,也就是在执行最后一个 ‘}’时,finalize()才被执行)

//: Main.java

/**
* 垃圾回收
* 注意: Java环境1.6可以, 1.8不可以, 垃圾回收机制改变.
*/ class Test {
@Override
protected void finalize(){
System.out.println("finalize");
// super.finalize();
}
} class Main {
public static void main(String[] args) {
Test t = new Test();
t = null; // 确保finalize()会被调用
System.gc();
}
}
/**
* Output:
finalize
*///:~

12

清理对象时, 会调用finalize()函数, 并且会保留存储数据, 如T2;
在清理对象时, 会入栈出栈, 先入后清理, 后入先清理.

//: Main.java

/**
* 垃圾回收
* 注意: Java环境1.6可以, 1.8不可以, 垃圾回收机制改变.
*/ class Tank {
boolean isFull = false;
String name;
Tank(String name) {
this.name = name;
}
void setEmpty() {
isFull = false;
}
void setFull() {
isFull = true;
} @Override
protected void finalize(){
if (!isFull) {
System.out.println(name + ": 清理");
}
// super.finalize();
}
} class Main {
public static void main(String[] args) {
Tank t1 = new Tank("T1");
Tank t2 = new Tank("T2");
Tank t3 = new Tank("T3");
t1.setFull();
t2.setEmpty();
t1 = null;
t2 = null;
t3 = null;
System.gc();
}
}
/**
* Output:
T3: 清理
T2: 清理
*///:~

20

//: OtherMain.java

/**
* 测试main的可变参数形式
* Created by wang on 15/7/30.
*/
public class OtherMain {
public static void main(String... args) {
for (String s : args) {
System.out.print(s + " ");
}
System.out.println();
}
}
/**
* Output:
* haha ahah haah ahha
*///:~