马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 回忆一遥远 于 2017-8-16 08:43 编辑
不能放弃
我已经受够什么事都只做一半的自己了 明明智商低,水平低还做特喵的什么鬼兼职,结果辞都辞不掉
Object 对象
Java 中所有的类都直接或间接继承 Object ,因此都有如下方法
getClass();
hashCode();
equals(Object obj);
clone();
toString();
notify();
notifyAll();
wait();
finalize();
getClass();
/**
* @return The {@code Class} object that represents the runtime
* class of this object.
*/
public final native Class<?> getClass();
调用此方法会返回这个实例所对应的对象名
例如:public class TestObject {
public static void main(String[] args) {
Student p = new Student(1, "小白");
System.out.println(p.getClass());
}
}
class Student{
int id;
String name;
public Person(int id, String name) {
this.id = new Integer(id);
this.name = new String(name);
}
}
结果是:
hashCode();
/**
* Returns a hash code value for the object. This method is
* supported for the benefit of hash tables such as those provided by
* @return a hash code value for this object.
* @see java.lang.Object#equals(java.lang.Object)
* @see java.lang.System#identityHashCode
*/
public native int hashCode();
计算一个实例的哈希码
即使一个类的两个实例的内部元素一样,哈希码也是不同的
例如:public class TestObject {
public static void main(String[] args) {
Student p = new Student(1, "小白");
Student p1 = new Student(1, "小白");
System.out.println(p.hashCode());
System.out.println(p1.hashCode());
}
}
class Student{
int id;
String name;
public Person(int id, String name) {
this.id = new Integer(id);
this.name = new String(name);
}
}
结果:
equals(Object obj);
public boolean equals(Object obj) {
return (this == obj);
}
由 Java src 可知,Object 的是否相等的判断方法是对比在堆中的位置是否相等,所以一般需要自己重载
例子~public class TestObject {
public static void main(String[] args) {
Student p = new Student(1, "小白");
Student p1 = new Student(1, "小白");
System.out.println(p.equals(p1));
}
}
class Student{
int id;
String name;
public Person(int id, String name) {
this.id = new Integer(id);
this.name = new String(name);
}
@Override // 这是重写的伪代码,会提示编译器检查代码的正确性
public boolean equals(Object obj) {
/*Student person = (Student)obj;
if(id == person.id && name == person.name)
return true;
return false;*/
Student person = (Student)obj;
if(id == person.id && name.equals(person.name)) return true;
return false;
}
}
结果 |