可能重复:
在Java中实现单例模式的有效方法
我正在阅读这篇关于Java的最佳单例实现,但它不是线程安全的.
根据维基:
if(singleton==null) { synchronized(Singleton.class) { // this is needed if two threads are waiting at the monitor at the // time when singleton was getting instantiated if(singleton==null) singleton= new Singleton(); }
}
但是Find Bugs实用程序在此中给出了两个错误:1.双重空检查.2.静态字段的延迟初始化不正确.
什么是最好的方法,
这是对的吗 :
Run Code Online (Sandbox Code Playgroud)synchronized (Singleton.class) { if (singleton== null) { singleton= new Singleton(); } }
初始化ArrayListJava 的最佳实践是什么?
如果我使用new运算符初始化ArrayList,则默认情况下ArrayList将为10个桶分配内存.这是一个性能打击.
我不知道,也许我错了,但在我看来ArrayList,如果我确定尺寸,我应该通过提及尺寸来创建!
方法签名是方法声明的一部分.它是方法名称和参数列表的组合.
因此,我只想传递一个构成所有参数的请求对象,而不是指定参数列表.对于所有方法可能都不是这样,但是想要在任何可能的地方尝试.
比如说
public void setMapReference(int xCoordinate, int yCoordinate)
{
//method code
}
Run Code Online (Sandbox Code Playgroud)
也可以写成
public void setMapReference(Point point)
{
//method code
}
Run Code Online (Sandbox Code Playgroud)
class Point {
int xCoordinate;
int yCoordinate;
boolean isValidPoint();
}
Run Code Online (Sandbox Code Playgroud)
但是调用者可能会因为他不知道参数而感到困惑.!!
这是一个好习惯吗?