我指的是维基百科上Bill Pugh的Singleton Pattern解决方案:
public class Singleton
{
// Private constructor prevents instantiation from other classes
private Singleton() {}
/**
* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class SingletonHolder
{
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance()
{
return SingletonHolder.INSTANCE;
}
}
Run Code Online (Sandbox Code Playgroud)
他们在这里提到:
内部类之前没有引用(因此不会被类加载器加载),而不是
getInstance()被调用的时刻.因此,该解决方案是线程安全的,无需特殊的语言结构(即volatile或synchronized).
但是,2个线程是否有可能getInstance()同时调用,这会导致创建两个单例实例?synchronized在这里使用不安全吗?如果是,那么它应该在代码中使用的位置?
我正在尝试编写一个扭转字符串的trival面试问题.
这是我的代码:
#include <string.h>
char* rev( char* str)
{
int i,j,l;
l = strlen(str);
for(i=0,j=l-1; i<l/2 ; i++, j--)
{
str[i] = (str[i] + str[j]);
str[j] = str[i] - str[j];
str[j] = str[i] - str[j];
}
return str;
}
int main()
{
char *str = " hello";
printf("\nthe reverse is %s ...", rev(str));
return 1;
}
Run Code Online (Sandbox Code Playgroud)
基本上,这个给出了分段错误.
我有以下问题:
我得到分段错误可能是因为,字符加起来没有在ascii中定义,因此我不能将它们存储为字符,我正在使用www.codepad.org [我想知道它是否支持ascii !!].我的理解是正确的还是还有别的东西.
我如何纠正问题,对于同一平台[我的意思是为codepad.org交换]
在这里,我必须使用额外的整数l来计算长度.所以通过交换来保存单个字符空间..我正在使用额外的int !!! ..只是为了给观众留下深刻印象:) ...这种做法前夕值得!
这个是针对那些有兴趣编写单元测试/ API测试的人.我希望有一个强大的实现,所以可能的测试用例.我假设如果面试官问这么简单的问题......他肯定想要一些非常抢劫的实施和测试用例.我很少想到:
传递空字符串传递整数
字符串传递整数数组而不是char数组.
很长的弦,
单个字符串字符串的特殊字符.
任何建议/建议都会有所帮助.