在阅读了c#的隐藏特性之后,我想知道Java的隐藏特性有哪些?
当前回答
如果你做了很多JavaBean开发,并且使用了属性更改支持,你通常会写很多这样的setter:
public void setFoo(Foo aFoo){
Foo old = this.foo;
this.foo = aFoo;
changeSupport.firePropertyChange("foo", old, aFoo);
}
我最近无意中发现了一篇博客,它提出了一个更简洁的实现,使代码更容易编写:
public void setFoo(Foo aFoo){
changeSupport.firePropertyChange("foo", this.foo, this.foo = aFoo);
}
它实际上简化了事情,以至于我能够在Eclipse中调整setter模板,从而自动创建方法。
其他回答
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应该插入的位置…它还允许您找到数组中“最接近”的匹配项。
我认为它很漂亮……:)
对于我面试的大多数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中只是一个关键字?:)
The power you can have over the garbage collector and how it manages object collection is very powerful, especially for long-running and time-sensitive applications. It starts with weak, soft, and phantom references in the java.lang.ref package. Take a look at those, especially for building caches (there is a java.util.WeakHashMap already). Now dig a little deeper into the ReferenceQueue and you'll start having even more control. Finally grab the docs on the garbage collector itself and you'll be able to control how often it runs, sizes of different collection areas, and the types of algorithms used (for Java 5 see http://java.sun.com/docs/hotspot/gc5.0/gc_tuning_5.html).
使用此关键字从内部类访问包含类的字段/方法。在下面的例子中,我们希望使用匿名内部类的容器类的sortAscending字段。使用ContainerClass.this.sortAscending代替this。sortAscending就是这样。
import java.util.Comparator;
public class ContainerClass {
boolean sortAscending;
public Comparator createComparator(final boolean sortAscending){
Comparator comparator = new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
if (sortAscending || ContainerClass.this.sortAscending) {
return o1 - o2;
} else {
return o2 - o1;
}
}
};
return comparator;
}
}
因为还没有人说过(我认为)我最喜欢的功能是自动装箱!
public class Example
{
public static void main(String[] Args)
{
int a = 5;
Integer b = a; // Box!
System.out.println("A : " + a);
System.out.println("B : " + b);
}
}
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder
- 将JSON字符串转换为HashMap