2024-04-20 09:00:01

Java的隐藏特性

在阅读了c#的隐藏特性之后,我想知道Java的隐藏特性有哪些?


当前回答

部分功能,部分麻烦:Java的String处理使其“看起来”是原生类型(使用运算符,+,+=)

能写的:

String s = "A";
s += " String"; // so s == "A String"

非常方便,但只是语法糖(即被编译为):

String s = new String("A");
s = new StringBuffer(s).append(" String").toString();

因此,一个对象实例化和2个方法调用一个简单的连接。想象一下以这种方式在循环中构建一个长字符串!?并且StringBuffer的所有方法都声明为同步的。谢天谢地,在Java 5中,他们引入了StringBuilder,它与StringBuffer是一样的,只是没有同步。

这样的循环:

String s = "";
for (int i = 0 ; i < 1000 ; ++i)
  s += " " + i; // Really an Object instantiation & 3 method invocations!

可以(应该)在你的代码中重写为:

StringBuilder buf = new StringBuilder(); // Empty buffer
for (int i = 0 ; i < 1000 ; ++i)
  buf.append(' ').append(i); // Cut out the object instantiation & reduce to 2 method invocations
String s = buf.toString();

并将运行大约80+%比原来的循环! (在我运行的一些基准测试中高达180%)

其他回答

strictfp关键字。(但我从未见过它在实际应用中使用:)

你可以使用下面的符号来获取基元类型的类: float.class等等。在做反射的时候非常有用。

Final数组可用于从匿名内部类中“返回”值(警告,下面的示例无用):

final boolean[] result = new boolean[1];
SwingUtilities.invokeAndWait(new Runnable() {
  public void run() { result[0] = true; }
});

在1.5中增加了for-each循环结构。我<3它。

// For each Object, instantiated as foo, in myCollection
for(Object foo: myCollection) {
  System.out.println(foo.toString());
}

并且可以在嵌套实例中使用:

for (Suit suit : suits)
  for (Rank rank : ranks)
    sortedDeck.add(new Card(suit, rank));

for-each结构也适用于数组,它隐藏了索引变量而不是迭代器。下面的方法返回int数组中所有值的和:

// Returns the sum of the elements of a
int sum(int[] a) {
  int result = 0;
  for (int i : a)
    result += i;
  return result;
}

链接到Sun文档

我个人很晚才发现java.lang.Void——结合泛型提高了代码的可读性,例如Callable<Void>

java.util.Arrays中的asList方法允许变量参数、泛型方法和自动装箱的良好组合:

List<Integer> ints = Arrays.asList(1,2,3);

不是Java语言的一部分,但是Sun的JDK附带的javap反汇编程序并不广为人知或被广泛使用。