Java clone()和equals()检查
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Java clone()和equals()检查,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1430字,纯文字阅读大概需要3分钟。
内容图文
![Java clone()和equals()检查](/upload/InfoBanner/zyjiaocheng/818/b38472cafe324a9b8df9b3244012bf4a.jpg)
对于下面的类,我理解c1.equals(c3)返回false,因为c1.clone()创建指向同一对象的不同引用.但为什么carList1.equals(carList2)返回true?为什么它与c1.equals(c3)不同?提前谢谢了!
class Car implements Cloneable {
private String plate;
private double maxSpeed;
public Car(String lp, double max) {
license = lp;
maxSpeed = max;
}
public static void main(String[] args) throws Exception{
Car c1 = new Car("ABC123", 150.0);
Car c2 = new Car("ABC123", 150.0);
Car c3 = (Car) c1.clone();
ArrayList<Car> carList1 = new ArrayList<Car>();
carList1.add(c1);
carList1.add(c2);
ArrayList carList2 = (ArrayList) carList1.clone();
}
}
解决方法:
ArrayList的clone执行浅拷贝,即它不克隆ArratList中包含的元素,它只是复制引用.这就是为什么equals返回true,因为它不比较ArrayList对象的引用,它比较列表中的元素.
public Object clone()
Returns a shallow copy of this ArrayList instance. (The elements
themselves are not copied.)public boolean equals(Object o)
Compares the specified object with this list for equality. Returns
true if and only if the specified object is also a list, both lists
have the same size, and all corresponding pairs of elements in the two
lists are equal. (Two elements e1 and e2 are equal if (e1==null ?
e2==null : e1.equals(e2)).) In other words, two lists are defined to
be equal if they contain the same elements in the same order.
另一方面,Car假设你没有覆盖它的equals方法来比较成员,使用Object :: equals的默认实现,它比较了对象引用,因此克隆的Car不等于原始的.
内容总结
以上是互联网集市为您收集整理的Java clone()和equals()检查全部内容,希望文章能够帮你解决Java clone()和equals()检查所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。