在此之前,我们要知道的是,String是不可变对象,只要创建就不能修改,所有的修改操作实际上都是新建的String对象.
1.直接赋值
String myString = "hello world";
原理是:现在java的常量池中寻找hello world对象,如果没有,在堆内存中new一个值为”hello world” 的对象,放到常量池中. 之后再用直接赋值的方法时,如果值相同,就直接引用这个对象,不用新建.
如果直接赋值的值相同,那么他们两个就是同一个对象
比如
String myString = "hello world";
String yourString = "hello world";
System.out.println("is same object?");
System.out.println(myString==yourString);
运行
2.用new新建对象
String myString = new String("hello world");
新建对象是直接在堆内存中新建一个对象,再赋值.用new新建对象的对象都不是同一个对象
String myString = new String("hello world");
String yourString = new String("hello world");
System.out.println("is same object?");
System.out.println(myString==yourString);
运行
3.补充:hashcode()方法
在上篇博文中,我想通过hashcode来从侧面验证他是不是同一个对象,但是发现不同对象的hashcode也可以相同=-=.也是今天才发现的,昨天没有仔细看.接下来,我们就看一下hashcode的定义吧.先给出源码
/**
* Returns a hash code for this string. The hash code for a
* {@code String} object is computed as
* <blockquote><pre>
* s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
* </pre></blockquote>
* using {@code int} arithmetic, where {@code s[i]} is the
* <i>i</i>th character of the string, {@code n} is the length of
* the string, and {@code ^} indicates exponentiation.
* (The hash value of the empty string is zero.)
*
* @return a hash code value for this object.
*/
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
发现了没有,hashcode是通过value生成的h = 31*h + val[i]
,所以只要value相同,hashcode就相同.hashcode但是可以验证一下equals方法.
这样,我们尝试着自己写一下hashcode,看看与String自带的hashcode是否相同
public static void hashcodeTest(){
String name = new String("yangqi");
char[] a = name.toCharArray();
int hash = 0;
//自己生成hashcode
for(int i = 0;i<name.length();i++){
hash = 31*hash + a[i];
}
System.out.println("myHashCode::"+hash);
System.out.println("current hashcode:"+name.hashCode());
}
运行结果:
4.那么,java中又没有唯一标识对象的变量或者标识
百度了半天,也看了看object的源码,没有在类的内部找到有定义唯一的标识.
那么,这么标识呢? 可以生成一个 UUID ,UUID介绍:https://blog.csdn.net/zheng963/article/details/42551265
使用方法:
String logid = java.util.UUID.randomUUID().toString();
当然,这个标识只能存在我们自定义的类中,而且声明必须为final 且不能为static
private final String suuid = UUID.randomUUID().toString();