关于java的Stack类的问题。

代码:如下
public static void main(String[] args)
{
Stack stack = new Stack<>();
stack.push(1);
stack.push(2);
System.out.println(stack.hashCode());// hashcode输出994
for (Integer i : stack)
{
System.out.println(i); // 输出1 2
}
changeStack(stack);
System.out.println(stack.hashCode());// hashcode输出32
for (Integer i : stack)
{
System.out.println(i);//输出1
}

}
public static void changeStack(Stack<Integer> stack)
{
    stack.pop();
}
    问题:
    为什么stack在changeStack()之后,居然连hashcode都变了呢?我知道stack的值会改变的,只是不知道为啥内存地址也会变,前后的hashcode不应该一样么?我用Stringbuffer类,对他append之后,前后的hashcode一样。为啥Stack会这样呢?

朋友,首先纠正一个问题,hashcode 值 并不是Stack的地址的引用,也不是Stack中元素的地址引用。根据继承关系分析,
Stack调用的AbstractList抽象类HashCode方法或者hashCode值。
图片说明
![图片说明
图片说明
从图中可以看出,HashCode值得计算并不是地址引用,但是跟元素的HashCode有关联,即元素的HashCode值参与了计算。
我们Stack中存在的元素是Integer类型,而Integer 类型的HashCode值实际上就上Integer的value,即我们存储的值,如图:
图片说明
经过这段介绍我想你应该可以可以理解了吧~

Stack的父类是Vector,Vector的父类是AbstractList,这个要看AbstractList的源码。看源码我们发现,其hashCode方法和元素是相关的,调用changeStack方法后,stack的元素发生变化,元素个数从1变为2,这样算出的hashCode值一定是不同的。
/**
* Returns the hash code value for this list.
*
*

This implementation uses exactly the code that is used to define the
* list hash function in the documentation for the {@link List#hashCode}
* method.
*
* @return the hash code value for this list
*/
public int hashCode() {
int hashCode = 1;
for (E e : this)
hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
return hashCode;
}