2024-04-20 09:00:01

Java的隐藏特性

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


当前回答

你可以在局部类的初始化块和方法中访问最终的局部变量和参数。考虑一下:

    final String foo = "42";
    new Thread() {
        public void run() {
             dowhatever(foo);
        }
    }.start();

有点像个了结,不是吗?

其他回答

语言级assert关键字。

对于我面试的大多数Java开发人员来说,标记为块的职位是非常令人惊讶的。这里有一个例子:

// code goes here

getmeout:{
    for (int i = 0; i < N; ++i) {
        for (int j = i; j < N; ++j) {
            for (int k = j; k < N; ++k) {
                //do something here
                break getmeout;
            }
        }
    }
}

谁说goto在java中只是一个关键字?:)

Self-bound泛型:

class SelfBounded<T extends SelfBounded<T>> {
}

http://www.artima.com/weblogs/viewpost.jsp?thread=136394

当你不需要StringBuilder中包含的同步管理时,使用StringBuilder代替StringBuffer。它将提高应用程序的性能。

Java 7的改进甚至比任何隐藏的Java特性都要好:

菱形语法:Link

不要在实例化时使用那些infinite <>语法:

Map<String, List<String>> anagrams = new HashMap<String, List<String>>();

// Can now be replaced with this:

Map<String, List<String>> anagrams = new HashMap<>();

switch中的字符串:Link

在switch中使用String,而不是old-C int:

String s = "something";
switch(s) {
 case "quux":
    processQuux(s);
    // fall-through

  case "foo":
  case "bar":
    processFooOrBar(s);
    break;

  case "baz":
     processBaz(s);
    // fall-through

  default:
    processDefault(s);
    break;
}

自动资源管理Link

这段旧代码:

static void copy(String src, String dest) throws IOException {
    InputStream in = new FileInputStream(src);
    try {
        OutputStream out = new FileOutputStream(dest);
        try {
            byte[] buf = new byte[8 * 1024];
            int n;
            while ((n = in.read(buf)) >= 0)
                out.write(buf, 0, n);
        } finally {
            out.close();
        }
    } finally {
        in.close();
    }
}

现在可以用更简单的代码代替:

static void copy(String src, String dest) throws IOException {
    try (InputStream in = new FileInputStream(src);
            OutputStream out = new FileOutputStream(dest)) {
        byte[] buf = new byte[8192];
        int n;
        while ((n = in.read(buf)) >= 0)
            out.write(buf, 0, n);
    }
}

我差点忘了这个小宝贝。在任何正在运行的java进程上尝试这个:

jmap -histo:活动PID

您将得到给定VM中活动堆对象的直方图。作为一种快速计算某些类型的内存泄漏的宝贵方法。我使用的另一种技术是创建和使用所有集合类的有大小限制的子类。这将导致容易识别的失控集合出现快速故障。