java常见代码(1)------常见实现方法
文章目录
1.equals 和 hashcode方法
class Students {
String name;
int age;
byte[] idSequence;
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Students))
return false;
Students other = (Students) obj;
return name.equals(other.name)
&& age == other.age
&& Arrays.equals(idSequence, other.idSequence);
}
@Override
public int hashCode() {
return name.hashCode() + age + Arrays.hashCode(idSequence);
}
}
文档链接:https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#equals-java.lang.Object-
- 对于Students任意的非null的对象stu,stu.equals(null),应该返回false; 而不应该抛出空指针异常,所以使用 instanceof来判断;
- 对于基本原始类型,比较用“==”;对于对象类型,比较用“equals()” 方法;
- 需要实现相应的hashcode()方法;
- 数组类型,应调用相应Arrays类里的方法
2.compareTo
class Person implements Comparable<Person> {
String firstName;
String lastName;
int birthdate;
@Override
public int compareTo(Person other) {
if (firstName.compareTo(other.firstName) != 0)
return firstName.compareTo(other.firstName);
else if (lastName.compareTo(other.lastName) != 0)
return lastName.compareTo(other.lastName);
else if (birthdate < other.birthdate)
return -1;
else if (birthdate > other.birthdate)
return 1;
else
return 0;
//可以用Integer.Compare(int, int) 代替;java7
}
}
文档链接:https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html
- 只有返回值的符号是重要的,所以不应该有判断返回值是否为
-1的语句出现; - 两个如int 类型做差比较来实现在不发生溢出的情况下是可行的;
3.clone
class Values implements Cloneable {
String letter;
double fol;
int[] numbers;
Date date;
public Values clone() {
try {
Values res = (Values) super.clone();
res.numbers = res.numbers.clone();
res.date = (Date) res.date.clone();
return res;
} catch (CloneNotSupportedException e) {
throw new AssertionError(e);
}
}
}
文档链接:https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#clone--
- 不用再为原始类型或者不可变类型来clone;
- 对其他字段进行clone(objects/arrays);
- 该接口中并无clone方法
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论