对于对象可以通过调用hashCode()得到内存地址。 primitive type变量我就不知道了。import java.util.*;public class InfiniteRecursion { public String toString() { return "address: " + Integer.toHexString(hashCode()) + "\n"; } public static void main(String[] args) { List v = new ArrayList(); for (int i = 0; i < 10; i++) v.add(new InfiniteRecursion()); System.out.println(v); } }
我说的是使用java.lang.object.hashCode(); 我刚学java,记得书中介绍说java对java.lang.object.hashCode();是通过返回对象在内存中的地址来实现的。 public class StrAddr { public static void main(String[] args) { String a = "123"; String b = "456"; System.out.println("String Value Address: " + Integer.toHexString(a.hashCode())); System.out.println("String Value Address: " + Integer.toHexString(b.hashCode())); } }
你知道String的hashCode()方法是怎么算出来的吗? Returns a hash code for this string. The hash code for a String object is computed as s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1不是对象的地址
primitive type变量我就不知道了。import java.util.*;public class InfiniteRecursion {
public String toString() {
return "address: " + Integer.toHexString(hashCode()) + "\n";
}
public static void main(String[] args) {
List v = new ArrayList();
for (int i = 0; i < 10; i++)
v.add(new InfiniteRecursion());
System.out.println(v);
}
}
比如String object其hashCode()得到的是String.toString()的结果!
我刚学java,记得书中介绍说java对java.lang.object.hashCode();是通过返回对象在内存中的地址来实现的。
public class StrAddr {
public static void main(String[] args) {
String a = "123";
String b = "456";
System.out.println("String Value Address: " + Integer.toHexString(a.hashCode()));
System.out.println("String Value Address: " + Integer.toHexString(b.hashCode()));
}
}
Returns a hash code for this string. The hash code for a String object is computed as
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1不是对象的地址
我想学过java的人都知道,java里面没有指针就是为了防止对内存的随意操纵,如果又存在某些方法能得到内存地址那岂不是自相矛盾?
这是个人意见,前提是我不知道怎么获取内存地址
public PassReferences() {
}
static void f(PassReferences h){
System.out.println("h inside f(): "+h);
} public static void main(String[] args){
PassReferences p = new PassReferences();
System.out.println("p inside main(): "+ p);
f(p); }}
这是thinking in java的例程,用来得到PassReferences对象的地址,调用了Object.toString()方法得到的是用户自定义对象PassReferences的地址;也就是说有的对象的内存地址是可以得到的,
假设一个Class中没有实现toString(),包括其除去Object以外的所有superclass,那么调用对象的toString方法也将得到其对象的内存地址但是却没有办法让一个类型的对象调用其父类型的函数,也就是关闭动态绑定,我看thinking in java说把函数声明为final可以关闭动态绑定,但是只是告诉compiler:动态绑定不需要,允许compiler根据final method call产生效率较佳的的程序代码,但是并不能保证compiler不使用动态绑定不知我的理解正确否?
getClass().getName() + '@' + Integer.toHexString(hashCode())
实际上是Object的hashCode方法返回对象的地址。所以在需要得到内存地址的类到Object之间如果没有类对hashCode进行覆盖(override),就可以通过该方法得到对象的内存地址。反之就无法通过此方法得到内存地址。
我觉得应该可以通过某个函数来得到对象或变量的内存地址,但我们不能通过该地址来操作它所存储的内容。
对于任何对象,直接调用下面这个方法不就获得的没有重写前的hashCode?
System.identityHashCode(Object obj);
两个对象值相同(x.equals(y) == true),但却可有不同的hash code,这句话对不对? 不对,有相同的hash code。
---------------------
个人认为hashCode是对象在内存中的唯一id,hashCode相等,说明就是同一对象
对于任何对象,直接调用下面这个方法不就获得的没有重写前的hashCode?
System.identityHashCode(Object obj);
---------------------
“没有重写前的hashCode”,什么意思啊?!