1.对于下面一段代码
package test;
public class exec {
public static void main(String[] args) {
// TODO Auto-generated method stub
Integer a=100;
Integer b =100;
Integer c=200;
Integer d=200;
System.out.println(a==b);
System.out.println(c==d);
long e =100L;
long f=100L;
long g=200L;
long h=200L;
System.out.println(e==f);
System.out.println(g==h);
}
}
输出的结果是:true flase true true
分析:第二个人为什么是false,由于在值范围内【-128,127】内是不会产生新的对象,直接把缓存中的对象拿来用,当值超过范围,就会产生一个新的对象。
来说说最后放100和放200的内存区域是不一样的,一个在data segment一个在堆内存。
2.交换两个值的方法:
四种方法:
第一个:通过第三个变量
int a=100,int b=200;
int temp;
temp=a;
a=b;
b=temp
第二个方法:加减法
int a=100,int b=200;
a=a+b;
b=a-b;
a=a-b;
第三个方法:地址算法
int *a,*b; //假设
*a=new int(10);
*b=new int(20);
*a=new int(10);
*b=new int(20);
if(a<b)
{
a=(int*)(b-a);
b=(int*)(b-(int(a)&0x0000ffff));
a=(int*)(b+(int(a)&0x0000ffff));
}
else
{
b=(int*)(a-b);
a=(int*)(a-(int(b)&0x0000ffff));
b=(int*)(a+(int(b)&0x0000ffff));
}
第四个方法:位运算
int a=10,b=12; //a=1010^b=1100;
a=a^b; //a=0110^b=1100;
b=a^b; //a=0110^b=1010;
a=a^b; //a=1100=12;b=1010;
此算法能够实现是由异或运算的特点决定的,通过异或运算能够使数据中的某些位翻转,其他位不变。这就意味着任意一个数与任意一个给定的值连续异或两次,值不变。
第五个方法:栈运算
int exchange(int x,int y)
{
stack S;
push(S,x);
push(S,y);
x=pop(S);
y=pop(S);
}
3.单例模式怎么实现的?
分析:单例模式是一个类只有一个实例
有五种实现方法:这里参考来自https://developer.ibm.com/alert-zh/
package singleton;
class LockSingleton{
private volatile static LockSingleton singleton;
private LockSingleton(){}
//详见:http://www.ibm.com/developerworks/cn/java/j-dcl.html
public static LockSingleton getInstance(){
if(singleton==null){
synchronized(LockSingleton.class){
if(singleton==null){
singleton=new LockSingleton();
}
}
}
return singleton;
}
}
/**
* 四、枚举,《Effective Java》作者推荐使用的方法,优点:不仅能避免多线程同步问题,而且还能防止反序列化重新创建新的对象
*/
enum EnumSingleton{
INSTANCE;
public void doSomeThing(){
}
}
/**
* 三、静态内部类 优点:加载时不会初始化静态变量INSTANCE,因为没有主动使用,达到Lazy loading
*/
class InternalSingleton{
private static class SingletonHolder{
private final static InternalSingleton INSTANCE=new InternalSingleton();
}
private InternalSingleton(){}
public static InternalSingleton getInstance(){
return SingletonHolder.INSTANCE;
}
}
/**
* 二、恶汉,缺点:没有达到lazy loading的效果
*/
class HungrySingleton{
private static HungrySingleton singleton=new HungrySingleton();
private HungrySingleton(){}
public static HungrySingleton getInstance(){
return singleton;
}
}
/**
* 一、懒汉,常用的写法
*/
class LazySingleton{
private static LazySingleton singleton;
private LazySingleton(){
}
public static LazySingleton getInstance(){
if(singleton==null){
singleton=new LazySingleton();
}
return singleton;
}
}