字符串的hascode值可以更改吗?

时间:2018-10-14 20:02:37

标签: java string hashcode

我需要一个帮助来了解String类,我编写了一个程序,其中我用new关键字创建了一个字符串,而另一个用文字创建了字符串,下面是程序。在这里,我的困惑是为什么字符串s(字面量为1)被更改了,因为字符串是不可变的,所以仅值必须更改哈希码被更改的原因。是因为有intern()方法,请帮助我理解这一点。

    String s = "xyz";
 String s1 = new String("abc"); 
System.out.println(s.hashCode()+"--> hashcode before literal string"); 

System.out.println(s1.hashCode()+"--> hashcode before new keyword string"); 

System.out.println(s+"--> before case S value "); 
s = s1; 
System.out.println(s+ "--> after case S value"); 

System.out.println(s.hashCode()+"--> hashcode after literal string"); 

System.out.println(s1.hashCode()+"--> hashcode after new keyword string");

此输出为

119193->哈希码,在文字字符串之前

96354->哈希码,在新的关键字字符串之前

xyz->在大小写S值之前

abc->大小写S后的值

96354->哈希码,在文字字符串之后

96354->哈希码,在新的关键字字符串之后

1 个答案:

答案 0 :(得分:1)

s对象的值是不可变的,并且将始终生成相同的哈希码。

在您的问题中,#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np from scipy.ndimage import gaussian_filter def generate_fake_data(): """Generate data that looks like an example given.""" xs = np.arange(0, 25, 0.05) ys = - 20 * 1./(1 + np.exp(-(xs - 5.)/0.3)) m = xs > 7. ys[m] = -20.*np.exp(-(xs - 7.)[m] / 5.) # add noise ys += np.random.normal(0, 0.2, xs.size) return xs, ys def main(): xs, ys = generate_fake_data() # smooth out noise smoothed = gaussian_filter(ys, 3.) # find the point where the signal goes above the background noise # level (assumed to be zero here). base = 0. std = (ys[xs < 3] - base).std() m = smoothed < (base - 3. * std) x0 = xs[m][0] y0 = ys[m][0] plt.plot(xs, ys, '.') plt.plot(xs, smoothed, '-') plt.plot(x0, y0, 'o') plt.show() if __name__ == '__main__': main() 不是一个具有两个不同哈希码的对象:它是一个设置为两个不同对象的变量。

相关问题