“==”和equals()的区别 和 交换两个变量的值
一个学期即将结束,回顾一下大一上的内容,发现最初的概念又有了些遗忘,这次就来回顾一下自己关于判断相等的理解,以及对交换两数值的理解。
初步理解“==”和equals()
==: 判断两个字符串在内存中首地址是否相同,即判断是否是同一个字符串对象
equals(): 比较存储在两个字符串对象中的内容是否一致
Integer i=128;
Integer j=128;
System.out.println(i==j);
结果为:false
Integer存在缓存机制,会自动将-128~127的integer对象缓存在Cache数组中,一旦调用Integer.valueOf(i)方法,且-128<=i<=127,则会自动到数组中拿出来,否则就会创建新的Integer对象
而如果用equals方法比较,会相等。因为integer重写了equals方法
关于如何实现swap方法
如果直接调用交换方法
1. public class SwapSample {
2.
3. /* 用Primitive变量作为形参,传值,无法完成swap */
4. public static void swap(int i, int j) {
5. int temp = i;
6. i = j;
7. j = temp;
8. System.out.println("swap int: i is " + i);
9. System.out.println("swap int: j is " + j);
10. }
11.
12. public static void main(String[] args) {
13. int i = 10;
14. int j = 20;
15. swap(i, j);
16. System.out.println("1 main: i is " + i);
17. System.out.println("1 main: j is " + j);
18. }
19. }
显然,,最后两行输出依然是i为10,j为20
因为参数传递时,将实参的值拷贝给形参以后,方法内是对形参的操作,改变了形参的值,最后在调用方法结束后就消除了,并不会对实参的值有影响。
可以选择自定义类,作为形参,来修改两个对象的属性值,使其实现值的交换。
代码如下:
21. class Int {
22. public int in;
23.
24. public Int(int in) {
25. this.in = in;
26. }
27. }
28.
29. public class SwapSample {
30.
31.
32. public static void swap(Int oi, Int oj) {
33. int temp = oi.in;
34. oi.in = oj.in;
35. oj.in = temp;
36.
37.
38. /*
39. * Int otemp=oi; oi=oj; oj=otemp;
40. *//这行代码不能完成交换
41. */
42. System.out.println("swap Int: oi.in is " + oi.in);
43. System.out.println("swap Int: oj.in is " + oj.in);
44. }
45.
46. public static void main(String[] args) {
47. Int oi = new Int(10);
48. Int oj = new Int(20);
49. swap(oi, oj);
50. System.out.println("3 main: oi.in is " + oi.in);
51. System.out.println("3 main: oj.in is " + oj.in);
52. }
53. }
这样,我们就能交换所需的值。(改变了形参指向的对象的属性)