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%)

其他回答

我投票给java.util.concurrent,因为它的并发集合和灵活的执行器允许线程池、计划任务和协调任务。DelayQueue是我个人最喜欢的,其中元素在指定的延迟后才可用。

timer和TimerTask可以安全地休息了。

而且,它不是完全隐藏的,而是在与日期和时间相关的其他类不同的包中。timeunit在纳秒、微秒、毫秒和秒之间转换时很有用。

它比通常的someValue * 1000或someValue / 1000读起来要好得多。

还没有人提到instanceof的实现方式是不需要检查null的。

而不是:

if( null != aObject && aObject instanceof String )
{
    ...
}

只使用:

if( aObject instanceof String )
{
    ...
}

每个类文件都以十六进制值0xCAFEBABE开始,以标识它是有效的JVM字节码。

(解释)

一个接口可以扩展多个接口,但一个类只能扩展一个类,这让我感到惊讶。

我喜欢方法的静态导入。

例如,创建以下util类:

package package.name;

public class util {

     private static void doStuff1(){
        //the end
     }

     private static String doStuff2(){
        return "the end";
     }

}

然后像这样使用它。

import static package.name.util.*;

public class main{

     public static void main(String[] args){
          doStuff1(); // wee no more typing util.doStuff1()
          System.out.print(doStuff2()); // or util.doStuff2()
     }

}

静态导入适用于任何类,甚至数学…

import static java.lang.Math.*;
import static java.lang.System.out;
public class HelloWorld {
    public static void main(String[] args) {
        out.println("Hello World!");
        out.println("Considering a circle with a diameter of 5 cm, it has:");
        out.println("A circumference of " + (PI * 5) + "cm");
        out.println("And an area of " + (PI * pow(5,2)) + "sq. cm");
    }
}