当前位置:网站首页>Common methods of object learning [clone and equals]
Common methods of object learning [clone and equals]
2022-07-27 20:26:00 【bigdata7】
List of articles
Object
Introduce :
Object Class is Java The parent of all classes inside , Any class inherits by default Object class . Due to all default inheritance , therefore extends Object omitted .
Be careful :Object Class
getClass(),wait(),notify(),notifyAll()And other methods are defined asfinaltype , Therefore, it cannot be inherited to rewrite .
clone():
summary :
Protection method , Implement shallow copy of objects , Only when Cloneable Interface to call this method , Otherwise throw CloneNotSupportedException abnormal .
Mainly JAVA In addition to 8 The basic types of parameters are value passing , Other class object passing parameters are all reference passing , Sometimes we don't want to change parameters in methods , This is what you need to replicate in the class clone Method ( Achieve deep replication ).
Original code :
protected native Object clone() throws CloneNotSupportedException;
clone and copy The difference between
hypothesis Now there is a Employee object ,Employee tobby =new Employee(“CMTobby”,5000)
Usually we have such an assignment Employee cindyelf=tobby, This time it's just simple copy For a moment reference,cindyelf and tobby All point to the same in memory object,
such cindyelf perhaps tobby Any operation of may affect the other party . For example , If we pass cindyelf.raiseSalary() The method has changed salary Domain value , that tobby adopt
getSalary() Method is the modified salary Domain value , Obviously, this is not what we want to see . We hope to get tobby An exact copy of , At the same time, the two do not affect each other , Now
We can use Clone To meet our needs .Employee cindy=tobby.clone(), A new Employee object , and tobby Have the same attribute values and methods .
Shallow Clone and Deep Clone
Clone How is it done ?Object In the implementation of an object Clone I know nothing about it , It simply performs domain to domain copy, This is it. Shallow Clone.
With Employee For example , It has a domain inside hireDay Variables that are not basic data types , It is a reference Variable , after Clone Then a new Date Type reference,
It points to the same... As the corresponding field in the original object Date object , In this way, the cloned class shares some information with the original class , If you modify the clone class Data The value of the object , Then the original Data The value of the object will also change , This is unreasonable , So we can start with Data Inside rewrite clone , And then in Employee Rewrite the clone again , This solves the problem of cloning only a part
// Clone method override deep clone【 Shallow clone sleeve shallow clone 】
package com.bigdata.practice0923;
public class Emp implements Cloneable {
String empNo;
private String eName;
......
/** * Shallow clone */
@Override
protected Emp clone() throws CloneNotSupportedException{
return (Emp)super.clone();
}
@Override
public String toString() {
return "Emp [empNo=" + empNo + ", eName=" + eName +"]";
}
}
package com.bigdata.practice0923;
public class Dept implements Cloneable{
private String deptNo;
private String dName;
private String loc;
// Attribute is a class object If multiple classes do not carry out a series of operations such as inheritance, rewriting and cloning If the cloned object is modified, the value of the object will be changed It's not a real clone, just
Emp emp;
......
/** * depp clone */
@Override
protected Dept clone() throws CloneNotSupportedException {
Dept d = (Dept)super.clone();
d.emp = emp.clone();
return d;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Dept) {
Dept d = (Dept) obj;
if (this.deptNo.equals(d.deptNo) && this.dName.equals(d.dName) && this.loc.equals(d.loc)) {
return true;
}else {
return false;
}
}
return false;
}
@Override
public String toString() {
return "Dept [deptNo=" + deptNo + ", dName=" + dName + ", loc=" + loc + ", emp=" + emp + "]";
}
}
clone Method protection mechanism
stay Object in Clone() Is declared to be protected Of , There is a certain reason to do so , With Employee Class, for example , By declaring as protected, You can guarantee that only Employee In class 【 Inheritance relationships 】 can “ clone ”Employee object
clone Use of methods
When to use shallow Clone, When to use deep Clone, This mainly depends on the nature of the domain of the specific object , Basic data type or reference variable【 Reference data type 】
call Clone() Class to which the object of the method belongs (Class) must implements Clonable Interface , Otherwise it's calling Clone Method will throw CloneNotSupportedException
String The class has been rewritten clone Method , You can use it directly
toString():
Original code :
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
use : Returns a string 【 Class name 、@ and Unsigned hexadecimal of the hash code of the object Show composition 】
Be careful : Use more , In general, subclasses have coverage
Example :
package com.bigdata.practice0922;
public class ObjectTest {
public static void main(String[] args) {
Object o1 = new Object();
System.out.println(o1.toString());
}
}
>>>>>:
java.lang.Object@3b192d32
equals():
Original code :
public boolean equals(Object obj) {
return (this == obj);
}
use :
stay Object Direct judgment this And obj Whether the value of itself is equal .【 call equals The object and equals The parameter of obj Whether the referenced object is the same object 】
Be careful :
The same object refers to the same storage unit in memory , Same back true, Otherwise return to false
Use :
If you want the same content in different memory, you need to return true, We need to override the parent class equals() Method ,String It has been rewritten , So the comparison is the content .
【Object Of equals It is essentially the same as double grade 】
Example :
package com.bigdata.practice0922;
public class ObjectTest {
public static void main(String[] args) {
String str = " China ";
String str1 = str;
System.out.println(str.equals(str1));
}
}
>>>>>>>:
true
Double equal sum equals Comparison :
- Object Of equals The essence is the same as double grade
- Double level comparison is whether the values stored in the stack are the same
- String Of equals rewrite Object Of , Compare the contents of the string 【 The value stored in the heap 】 Are they the same? 【 Character array 】
- String It has been rewritten equals Method
package com.bigdata.practice0923;
public class EqualsTest {
public static void main(String[] args) {
// Object Of equals The essence is the same as double grade
// String It has been rewritten equals In fact, there is only one copy of the same content in the heap In different ways (hash Address ) To store operations
String str = " China ";
String str1 = " China ";
String str2 = new String(" China ");
String str3 = new String(" China ");
// Double level comparison is whether the values stored in the stack are the same
// 【 Direct value Constant pool hash With the first address of the array new It's in the pile hash With the first address of the array 】
// 【String Medium equals It is to judge whether it is the same by comparing the values of character arrays one by one 】
System.out.print(" A string that is directly initialized with the same double content :");
System.out.println(str == str1);
System.out.print(" If the contents of both classes are the same, you can directly give a value new The string that comes out :");
System.out.println(str == str2);
System.out.print(" Double class content is the same new The string that comes out :");
System.out.println(str2 == str3);
// String Of equals rewrite Object Of , The comparison is whether the contents of the string are the same
System.out.println("equals:");
System.out.println(str.equals(str1));
System.out.println(str.equals(str2));
System.out.println(str2.equals(str3));
}
}
- rewrite equals:
/** * rewrite equals Method */
@Override
public boolean equals(Object obj) {
if (obj instanceof Dept) {
Dept d = (Dept) obj;
if (this.deptNo.equals(d.deptNo) && this.dName.equals(d.dName) && this.loc.equals(d.loc)) {
return true;
}else {
return false;
}
}
return false;
}
package com.bigdata.practice0923;
public class EqualsTest2 {
public static void main(String[] args) {
Dept d1 = new Dept("N001", " Development Department ", " lanzhou ");
Dept d2 = new Dept("N001", " Development Department ", " lanzhou ");
System.out.println(d1 == d2); // false
// System.out.println(d1.equals(d2)); // false This equals Parent class Object Of The nature and == identical
// rewrite equals after
System.out.println(d1.equals(d2)); // true
}
}
边栏推荐
- es6删除对象的属性_ES6删除对象中的某个元素「建议收藏」
- Homology and cross domain
- 图解LeetCode——592. 分数加减运算(难度:中等)
- Standing on the shoulders of giants to learn, jd.com's popular architect growth manual was launched
- OA项目之我的审批(查询&会议签字)
- 多点双向重发布及路由策略的简单应用
- What does bus mean
- Source code analysis of Chang'an chain data storage
- ECU software and hardware architecture
- PyQt5快速开发与实战 4.5 按钮类控件 and 4.6 QComboBox(下拉列表框)
猜你喜欢

多点双向重发布及路由策略的简单应用

Use cpolar to build a business website (5)

C语言--数组

图解LeetCode——592. 分数加减运算(难度:中等)

ECU software and hardware architecture

发布2年后涨价100美元,Meta Quest 2的逆生长

Preprocessing and macro definition

#yy关于鱼的英文学习

Wu Hequan: digital technology empowering "double carbon" practice according to local conditions

Datepicker date selector in viewui compatible solution in ie11 browser
随机推荐
Can software testing be learned in 2022? Don't learn, software testing positions are saturated
MLX90640 红外热成像仪测温传感器模块开发笔记(七)
使用cpolar建立一个商业网站(5)
Kubectl's access to pod logs -- the way to build a dream
JD: get the raw data API of commodity details
C language POW function (how to play exponential function in C language)
发布2年后涨价100美元,Meta Quest 2的逆生长
内置函数时间日期函数
Built in function time date function
PC Museum (3) MITs Altair 8800
Huawei's 150 member team rushed to the rescue, and Wuhan "Xiaotangshan" 5g base station was quickly opened!
Codeworks 5 questions per day (average 1500) - day 24
Office automation solution - docuware cloud is a complete solution to migrate applications and processes to the cloud
数仓搭建——DWD层
You can understand it at a glance, eslint
Assignment 1 - Hello World ! - Simple thread Creation
传英特尔将停掉台积电16nm代工的Nervana芯片
ES6 deleting attributes of objects_ ES6 delete an element "suggested collection" in the object
[map set]
多点双向重发布及路由策略的简单应用