例如,请看一下Google I / O '17“ Android Animations Spring to Life”中的幻灯片:
SpringForce force = new SpringForce(0)
.setDampingRation(0.4f)
.setStiffness(500f);
for (int i = 0; i < heads.getChildCount(); i++) {
View child = heads.getChildAt(i);
SpringAnimation anim;
anim = new SpringAnimation(child, DynamicAnimation.ROTATION);
anim.setSpring(force).setStartValue(-25).start();
}
在那里我们可以看到在一行上定义了变量
anim
,在下一行上创建了该变量的实例。有时我在某些开源项目中也看到了这种方法。使用这种方法是否有真正的好处,或者仅仅是样式或可读性的问题?或者,对于幻灯片,是否适合幻灯片的宽度?但是如果是这样的话,他们可能会写类似:
SpringAnimation anim = new SpringAnimation(
child, DynamicAnimation.ROTATION);
最佳答案
让我们做一个小实验。给定以下两类:
public class Test {
public static void main(String... args) {
Integer i = Integer.valueOf(1);
System.out.println(i);
}
}
public class Test2 {
public static void main(String... args) {
Integer i;
i = Integer.valueOf(1);
System.out.println(i);
}
}
我们可以看一下生成的字节码:
> javac *.java && javap -c *.class
Compiled from "Test.java"
public class Test {
public Test();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String...);
Code:
0: iconst_1
1: invokestatic #2 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
4: astore_1
5: getstatic #3 // Field java/lang/System.out:Ljava/io/PrintStream;
8: aload_1
9: invokevirtual #4 // Method java/io/PrintStream.println:(Ljava/lang/Object;)V
12: return
}
Compiled from "Test2.java"
public class Test2 {
public Test2();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String...);
Code:
0: iconst_1
1: invokestatic #2 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
4: astore_1
5: getstatic #3 // Field java/lang/System.out:Ljava/io/PrintStream;
8: aload_1
9: invokevirtual #4 // Method java/io/PrintStream.println:(Ljava/lang/Object;)V
12: return
}
由于生成的字节码相同,因此这是个人喜好问题。