Java中swap()實現
1.今天可愛的譚老師發了一道題目,使用java寫方法交換Integer類型數據,而且入參固定了,題目請下圖:

入參固定的話,當時想到的是重新定義一個自己的Integer類型,讓它有get和set方法,直到看到賀大神,代碼如下:
public static void swap(Integer a,Integer b) throws Exception
{
Field field = Integer.class.getDeclaredField("value");
field.setAccessible(true);
field.setInt(a, a ^ b);
field.setInt(b, a ^ b);
field.setInt(a, a ^ b);
}
當時驚為天人,反射還能這么用的,還能修改final修飾的值,
特此記下!
然后譚老師發布來了他的答案,只有兩行,實現了需求,我也驚為天人
public static void swap(Integer a,Integer b) throws Exception
{
System.out.println("后a = " + b +"后b = " + a);
System.exit(0);
}
View Code
果然,知識和智慧是不可或缺的!
哈哈哈!
2.最后出來一個問題,set()和setInt()到底區別在哪里,兄弟們可以探討下,因為用set方法后結果不是咱們想要的
public static void swap3(Integer a,Integer b) throws Exception
{
Field field = Integer.class.getDeclaredField("value");
field.setAccessible(true);
Integer tmp = a;
field.set(a, b);
field.set(b, tmp);
}
最后,歡迎各位留言,歡迎大神解答!