码迷,mamicode.com
首页 > 其他好文 > 详细

史上最简单的一道面试题!坑人吧

时间:2018-06-01 01:00:31      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:new   creat   exce   面试   面试题   lock   ati   结束   sys   

把下面a,b值互换,使打印结果为a=2,b=1.

import java.lang.reflect.Field;

/**
 * Created by 70416 on 2018/4/7.
 */
public class App {
    public static void swap(Integer i1,Integer i2) throws NoSuchFieldException, IllegalAccessException {
      .....
    }
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Integer a=1,b=2;
        System.out.println("开始a="+a+",b="+b);
        swap(a,b);
        System.out.println("结束a="+a+",b="+b);
    }
}

技术分享图片

Field field = Integer.class.getDeclaredField("value");
field.setAccessible(true);
int tmp = i1.intValue();    
field.set(i1,i2.intValue());
field.set(i2,tmp);

技术分享图片
技术分享图片

import java.lang.reflect.Field;

/**
 * Created by 70416 on 2018/4/7.
 */
public class App {
    public static void swap(Integer i1,Integer i2) throws NoSuchFieldException, IllegalAccessException {
        Field field = Integer.class.getDeclaredField("value");
        field.setAccessible(true);
        Integer tmp = new Integer(i1.intValue());
        // int tmp = i1.intValue();    //Integer -127----128里的值这个就不行,指针指向了缓存里的值。
        field.set(i1,i2.intValue());
        field.set(i2,tmp);

    }
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Integer a=1,b=2;
//        System.out.println(a==b); //Integer -127----128里的相同值,答案为true,超出缓存为false。
        System.out.println("开始a="+a+",b="+b);
        swap(a,b);
        System.out.println("结束a="+a+",b="+b);
    }
}

技术分享图片

史上最简单的一道面试题!坑人吧

标签:new   creat   exce   面试   面试题   lock   ati   结束   sys   

原文地址:https://www.cnblogs.com/ttzzyy/p/9119788.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!