java 实现方法_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);

}

}

对于Students任意的非null的对象stu,stu.equals(null),应该返回false; 而不应该抛出空指针异常,所以使用 instanceof来判断;

对于基本原始类型,比较用“==”;对于对象类型,比较用“equals()” 方法;

需要实现相应的hashcode()方法;

数组类型,应调用相应Arrays类里的方法

2.compareTo

class Person implements Comparable {

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

}

}

只有返回值的符号是重要的,所以不应该有判断返回值是否为-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);

}

}

}

不用再为原始类型或者不可变类型来clone;

对其他字段进行clone(objects/arrays);

该接口中并无clone方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值