2024-04-20 09:00:01

Java的隐藏特性

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


当前回答

我喜欢方法的静态导入。

例如,创建以下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");
    }
}

其他回答

语言级assert关键字。

c风格的printf():)

System.out.printf("%d %f %.4f", 3,Math.E,Math.E);

输出: 3 2.718282 2.7183

二分搜索(以及它的返回值)

int[] q = new int[] { 1,3,4,5};
int position = Arrays.binarySearch(q, 2);

类似于c#,如果在数组中没有找到'2',它会返回一个负值,但如果你对返回值取1的补,你实际上会得到'2'可以插入的位置。

在上面的例子中,position = -2, ~position = 1,这是2应该插入的位置…它还允许您找到数组中“最接近”的匹配项。

我认为它很漂亮……:)

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

而不是:

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

只使用:

if( aObject instanceof String )
{
    ...
}

同一个类的实例可以访问其他实例的私有成员:

class Thing {
  private int x;

  public int addThings(Thing t2) {
    return this.x + t2.x;  // Can access t2's private value!
  }
}

泛型方法的类型参数可以像这样显式指定:

Collections.<String,Integer>emptyMap()