当我试着写这样的东西时:
public interface MyInterface {
static {
System.out.println("Hello!");
}
}
Run Code Online (Sandbox Code Playgroud)
编译器无法编译它.
但是当我写这样的东西时:
interface MyInterface {
Integer iconst = Integer.valueOf(1);
}
Run Code Online (Sandbox Code Playgroud)
并反编译它,我看到静态初始化:
public interface MyInterface{
public static final java.lang.Integer i;
static {};
Code:
0: iconst_1
1: invokestatic #1; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
4: putstatic #2; //Field i:Ljava/lang/Integer;
7: return
}
Run Code Online (Sandbox Code Playgroud)
你能告诉我这个行为吗?
我正在研究OpenJDK的来源.
我的注意力被这些方法所吸引,Byte.compare()并且Integer.compare():
public static int Byte.compare(byte x, byte y) {
return x-y;
}
public static int Integer.compare(int x, int y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
Run Code Online (Sandbox Code Playgroud)
该方法为什么Byte.compare()而Integer.compare()有不同的实现?
受这个问题的启发,我写了测试:
public class Main {
private static final long TEST_NUMBERS = 5L;
private static final long ITERATION_NUMBER = 100000L;
private static long value;
public static void main(final String [] args) throws Throwable {
for(int i=0; i<TEST_NUMBERS; i++) {
value = 0;
final Thread incrementor = new Thread(new Incrementor());
final Thread checker = new Thread(new Checker());
incrementer.start();
checker.start();
checker.join();
incrementer.join();
}
}
static class Incrementor implements Runnable {
public void run() {
for(int i=0; i<ITERATION_NUMBER; i++){
++value;
}
} …Run Code Online (Sandbox Code Playgroud) 为什么hash table(java.util.HashMap)按long,int,byte和short排序?
见下面的代码:
public class Main {
private static final int INITIAL_CAPACITY = 10;
public static void main(String[] args) {
final Map<Long, Long> longMap = new HashMap<>(INITIAL_CAPACITY);
final Map<Integer, Integer> integerMap = new HashMap<>(INITIAL_CAPACITY);
final Map<Byte, Byte> byteMap = new HashMap<>(INITIAL_CAPACITY);
final Map<Short, Short> shortMap = new HashMap<>(INITIAL_CAPACITY);
final Map<Double, Double> doubleMap = new HashMap<>(INITIAL_CAPACITY);
final Map<Float, Float> floatMap = new HashMap<>(INITIAL_CAPACITY);
final Map<BigDecimal, BigDecimal> bigDecimalMap = new HashMap<>(INITIAL_CAPACITY);
final …Run Code Online (Sandbox Code Playgroud) 我有代码:
class Test {
public static void main(final String [] args) {
System.out.println(foo());
}
private static int foo() {
int a = 0;
try {
++a;
return a;
} finally {
a = 10;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我无法理解为什么打印1.