前言: 首先明确Java中万物都是类。而对于类的赋值,一直都很疑惑,因此总结一下
一个例子
图示
先贴一张图
程序实现:
对int
型做测试,输出其值
和地址
。
- C:
#include<stdio.h>
using namespace std;
int main(){
int a, b;
a = 1;
b = 2;
printf("a = %d; address of a: %d; b = %d, address of b: %d\n", a, b, &a,&b);
a = b;
printf("a = %d; address of a: %d; b = %d, address of b: %d\n", a, b, &a,&b);
b = 3;
printf("a = %d; address of a: %d; b = %d, address of b: %d\n", a, b, &a,&b);
}
输出:
- Java
public class Main {
public static void main(String[] args) {
int a, b;
//这里若加下面这句会报错,因为java中万物皆对象,我们还未给其实例化。但是C中我们可以打印
// System.out.printf("a = %d; address of a: %d; b = %d, address of b: %d\n", a, b, System.identityHashCode(a), System.identityHashCode(b));
a = 1;
b = 2;
System.out.printf("a = %d; address of a: %d; b = %d, address of b: %d\n", a, b, System.identityHashCode(a), System.identityHashCode(b));
a = b;
System.out.printf("a = %d; address of a: %d; b = %d, address of b: %d\n", a, b, System.identityHashCode(a), System.identityHashCode(b));
a = 3;
System.out.printf("a = %d; address of a: %d; b = %d, address of b: %d\n", a, b, System.identityHashCode(a), System.identityHashCode(b));
}
}
输出
- 可以看到,虽然a和b的值最后结果一样,可是他们的地址的变换却是不一样的。我们看到C中由于
int
不是一个对象,因此地址没有改变,但是Java中却改变了。 - 而且值得注意的是
a=3
这一句,实际上已经重新创建了一个对象, 所以说,虽然地址层不一样,但是实际实现效果一样,但是java由于地址转换多次,所以很耗内存。
而Java中的类和C++中的类=
赋值还不一样
#include<stdio.h>
#include<iostream>
using namespace std;
class INT{
public:
int x;
INT(int num){
x = num;
}
};
int main(){
INT a = INT(1);
INT b = INT(2);
printf("a = %d; address of a: %d; b = %d, address of b: %d\n", a.x, b.x, &a,&b);
a = b;
printf("a = %d; address of a: %d; b = %d, address of b: %d\n", a.x, b.x, &a,&b);
a = INT(3);
printf("a = %d; address of a: %d; b = %d, address of b: %d\n", a.x, b.x, &a,&b);
}
输出:
- 可以看到地址依旧没变。这是因为:在C++中
B=A;
, 是把对象A的数据成员的值逐位复制给对象B
Java大数类
- 类声明、初始化三个阶段。如图
Java中的类=
赋值,实际上是指向地址的转换,所以Java大数类的赋值可以当做C中的普通整数赋值操作,虽然地址不一样了,但是值一样。
package acm;
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int m;
String s;
BigInteger a,b;
BigInteger inf = new BigInteger("111111111111");
a = BigInteger.valueOf(4);
b = BigInteger.valueOf(5);
System.out.printf("a = %d; address of a: %d; b = %d, address of b: %d\n", a, System.identityHashCode(a), b, System.identityHashCode(b));
a = b;
System.out.printf("a = %d; address of a: %d; b = %d, address of b: %d\n", a, System.identityHashCode(a), b, System.identityHashCode(b));
a = inf;
System.out.printf("a = %d; address of a: %d; b = %d, address of b: %d\n", a, System.identityHashCode(a), b, System.identityHashCode(b));
}
}
输出