《Java技术》实验六
当程序中出现异常时,JVM会依据方法调用顺序依次查找有关的错误处理程序。可使用printStackTrace 和getMessage方法了解异常发生的情况。阅读下面的程序,说明printStackTrace方法和getMessage 方法的输出结果分别是什么?并分析异常的传播过程。
printStackTrace输出结果为:
java.lang.Exception: Exception thrown in method3
at excise.PrintExceptionStack.method3(PrintExceptionStack.java:28)
at excise.PrintExceptionStack.method2(PrintExceptionStack.java:24)
at excise.PrintExceptionStack.method1(PrintExceptionStack.java:20)
at excise.PrintExceptionStack.main(PrintExceptionStack.java:6)
异常的传播过程
发生错误的代码放进try语句块中,catch语句块捕获这个异常;执行catch语句块,处理异常的语句,throw关键字是人为的抛出异常,在try里实例化抛出异常的对象,在catch中输出。
阅读下面程序,分析程序的运行结果,解释产生错误的原因,如果删除的是books集合的最后一个对象,运行的结果又是什么?你能对此作出解释吗?如果在遍历时非要删除集合中的元素,应如何实现?
如果删除最后一个对象,运行结果
原始元素之后:[One book, Two book, Three book]
One book
Two book
Three book
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:819)
at java.util.ArrayList$Itr.next(ArrayList.java:791)
at excise.Test2.main(Test2.java:14)
若想要删除,使用迭代器的remove方法进行删除
代码如下:
import java.util.*;
public class Test {
public static void main(String[] args) {
Collection
books.add("One book");
books.add("Two book");
books.add("Three book");
System.out.println("原始元素之后:" + books);
Iterator
while (it.hasNext()) {
String book = (String) it.next();
System.out.println(book);
if (book.equals("One book")) {
it.remove();
}
}
System.out.println("移除元素之后:" + books);
}
}
HashSet存储的元素是不可重复的。运行下面的程序,分析为什么存入了相同的学生信息?如果要去掉重复元素,应该如何修改程序。
对象内容引用不同所以出现相同信息
重写hashcode和equals
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
代码托管: https://git.oschina.net/ybyyy/saas.git
截图:
浙公网安备 33010602011771号