zoukankan      html  css  js  c++  java
  • 史上最简单的一道面试题!坑人吧

    把下面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);
        }
    }
    

  • 相关阅读:
    SpringBoot之使用外部的启动类
    CCF——最小差值(2017-12)
    CCF——买菜(2018-09)
    CCF——卖菜(2018-09)
    2792. Grammar Lessons
    2756. Lucky Transformation
    2776. String Task
    2794. Petya and Strings
    2810. Palindromic Times
    14. Football
  • 原文地址:https://www.cnblogs.com/ttzzyy/p/9119788.html
Copyright © 2011-2022 走看看