1. 请写出下述代码的输出
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
for (int i = 0;i<10;i++){
list.add(i);
}
System.out.println(list.size());
for (Integer tmp : list){
list.remove(tmp);
}
System.out.println(list);
}
结果:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList$Itr.next(ArrayList.java:851)
10
at com.taotao.common.pojo.Test.main(Test.java:17)
原因:集合不可以一边遍历一边删除
2. 请写出下述代码的输出
public class Test {
private String entry;
static {
System.out.println(1);
}
public Test() {
System.out.println(2);
}
public Test(String entry) {
this.entry = entry;
System.out.println(3);
System.out.println(3 + entry);
}
public static void main(String[] args) {
Test t = new Test("1");
System.out.println(5);
}
}
结果:
1
3
31
5
3. 请写出下述代码的输出
public static void main(String[] args) {
String[] array = new String[3];
array[1] = "1";
array[2] = "2";
array[3] = "3";
for (String tmp : array){
System.out.println(tmp);
}
}
结果:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at com.taotao.common.pojo.Test.main(Test.java:15)
原因:java中的数组长度一旦被初始化,就不可更改。
4. 请写出下述代码的输出
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
int a = 0;
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (Exception e) {
}
a++;
System.out.println("t1=" + a);
}
});
Thread t2 = new Thread(new Runnable() {
int a = 0;
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (Exception e) {
}
--a;
System.out.println("t2=" + a);
}
});
t1.run();
t2.run();
}
结果:
t1=1
t2=-1
拓展:调用Thread的run方法表示按顺序执行,如果将run改成start,两个线程会交叉执行,也就是说还会出现下面的显示结果。
t2=-1
t1=1
- 请写出下述 代码的输出
public static void main(String[] args) {
System.out.println(1 == 1); //true
System.out.println(1 == new Integer(1)); //true
System.out.println("a" == "a"); //true,"a"是被指向的对象存在于内存之中,后面的"a"还是从同一个对象里把值用来作比较,所以是true
System.out.println("a" == new String("a")); //false
System.out.println(new Integer(1).equals(1)); //true
System.out.println(new Integer(1).equals("1")); //false
}
equals源码:
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
网友评论