当前位置:网站首页>[question 31] create two identical pets
[question 31] create two identical pets
2022-04-21 07:48:00 【Xiaoxuzhu】
List of articles
zero 、 Preface
Today is learning JAVA Language The first time to punch in 31 God , Every day I will provide an article for group members to read ( You don't need to pay for a subscription ), After reading the article , According to the idea of problem solving , Do it again . stay Xiaoxuzhu JAVA Community Corresponding 【 Card printing 】 Clock in , Today's task is finished .
Because we all study the same article together , So you can ask any questions in the group , Small partners in the group can help you quickly , One can walk very fast , A group of people can go far , There are comrades in arms who study and communicate together , What a lucky thing .
After learning , Write your own study report blog , Can be published to Xiaoxuzhu JAVA Community , For the reference of the students .
My learning strategy is very simple , Strategy sea + Feynman method of learning . If you can put this 100 All the questions are realized by yourself , That means JAVA Language The foundation has been built successfully . Later advanced learning , You can continue to follow me , Go to the road of architect together .
One 、 Title Description
subject : The complexity of life , Finding as like as two peas is impossible. . But in JAVA in , You can judge whether an object is the same by comparing its member variables . This topic will create 3 A pet cat , By comparing their names 、 Age 、 Weight and color attributes to see if they are the same .
Two 、 Their thinking
Write a class , be known as Cat.
stay Cat Definition in class 4 Member variables , They are names 、 Age 、 Weight and color properties
Provide construction methods to set these property values
rewrite equals() Methods and toString() Method .
- rewrite equals Method is to compare whether two objects are the same
- rewrite toString The method is to directly Output object
Java All classes are Object A direct or indirect subclass of a class .Object Class equals Method , Used to compare whether two objects are the same . The default implementation of this method is to compare whether two objects are the same object .
So when we define a class , It is recommended to rewrite this equals Method .
3、 ... and 、 Code details
public class Cat {
private String name; // Indicates the name of the cat
private int age; // Indicates the age of the cat
private double weight; // Indicates the weight of the cat
private Color color; // Represents the color of the cat
public Cat(String name, int age, double weight, Color color) {
// Initialize cat properties
this.name = name;
this.age = age;
this.weight = weight;
this.color = color;
}
@Override
public boolean equals(Object obj) {
// Use attributes to determine whether cats are the same
if (this == obj) {
// If two cats are the same object, they are the same
return true;
}
if (obj == null) {
// If one of the two cats is null Is different
return false;
}
if (getClass() != obj.getClass()) {
// If two cats have different types, they are different
return false;
}
Cat cat = (Cat) obj;
return name.equals(cat.name) && (age == cat.age)
&& (weight == cat.weight) && (color.equals(cat.color));// Compare cat attributes
}
@Override
public String toString() {
// rewrite toString() Method
StringBuilder sb = new StringBuilder();
sb.append(" name :" + name + "\n");
sb.append(" Age :" + age + "\n");
sb.append(" weight :" + weight + "\n");
sb.append(" Color :" + color + "\n");
return sb.toString();
}
}
Test class
public class Test {
public static void main(String[] args) {
Cat cat1 = new Cat("Java", 12, 21, Color.BLACK);// Create a cat 1 Number
Cat cat2 = new Cat("C++", 12, 21, Color.WHITE); // Create a cat 2 Number
Cat cat3 = new Cat("Java", 12, 21, Color.BLACK);// Create a cat 3 Number
System.out.println(" The cat 1 Number :" + cat1);// Output cat 1 Number
System.out.println(" The cat 2 Number :" + cat2);// Output cat 2 Number
System.out.println(" The cat 3 Number :" + cat3);// Output cat 3 Number
System.out.println(" The cat 1 Whether the number is with the cat 2 Same number :" + cat1.equals(cat2));// Compare whether it is the same
System.out.println(" The cat 1 Whether the number is with the cat 3 Same number :" + cat1.equals(cat3));// Compare whether it is the same
}
}

solution 2: rewrite hashCode() Method
Their thinking
Java The created object is saved in the heap , To speed up the search , Hash lookup used . Is to define a key to map the memory address of the object . When you need to find this object , Find the key directly . You don't have to traverse the heap to find this object .
Write a class , be known as Cat2.
stay Cat2 Definition in class 4 Member variables , They are names 、 Age 、 Weight and color properties
Provide construction methods to set these property values
rewrite equals() Methods and hashCode() Method .
- rewrite equals Method is to compare whether two objects are the same
- rewrite hashCode You can save the same objects in the same location .
A simple method of calculating hash code :
- rewrite equals Method
- Multiply these member variables by different prime numbers and sum them
- This can be used as a new hash code .
Code details
public class Cat2 {
private String name; // Indicates the name of the cat
private int age; // Indicates the age of the cat
private double weight; // Indicates the weight of the cat
private Color color; // Represents the color of the cat
public Cat2(String name, int age, double weight, Color color) {
// Initialize cat properties
this.name = name;
this.age = age;
this.weight = weight;
this.color = color;
}
@Override
public boolean equals(Object obj) {
// Use attributes to determine whether cats are the same
if (this == obj) {
// If two cats are the same object, they are the same
return true;
}
if (obj == null) {
// If one of the two cats is null Is different
return false;
}
if (getClass() != obj.getClass()) {
// If two cats have different types, they are different
return false;
}
Cat2 cat = (Cat2) obj;
return name.equals(cat.name) && (age == cat.age)
&& (weight == cat.weight) && (color.equals(cat.color));// Compare cat attributes
}
@Override
public int hashCode() {
// rewrite hashCode() Method
return 7 * name.hashCode() + 11 * new Integer(age).hashCode() + 13
* new Double(weight).hashCode() + 17 * color.hashCode();
}
}
Test class :
public class Test2 {
public static void main(String[] args) {
Cat2 cat1 = new Cat2("Java", 12, 21, Color.BLACK); // Create a cat 1 Number
Cat2 cat2 = new Cat2("C++", 12, 21, Color.WHITE); // Create a cat 2 Number
Cat2 cat3 = new Cat2("Java", 12, 21, Color.BLACK); // Create a cat 3 Number
System.out.println(" The cat 1 Hash number of :" + cat1.hashCode());// Output cat 1 Hash number of
System.out.println(" The cat 2 Hash number of :" + cat2.hashCode());// Output cat 2 Hash number of
System.out.println(" The cat 3 Hash number of :" + cat3.hashCode());// Output cat 3 Hash number of
System.out.println(" The cat 1 Whether the number is with the cat 2 Same number :" + cat1.equals(cat2));// Compare whether it is the same
System.out.println(" The cat 1 Whether the number is with the cat 3 Same number :" + cat1.equals(cat3));// Compare whether it is the same
}
}

Four 、 Recommendation column
《JAVA From zero to one 》 Lesson four : Class and object Foundation
《JAVA From zero to one 》 Lecture 7 : Advanced object-oriented features
5、 ... and 、 Sample source code download
Pay attention to the official account below. , Restoration and foundation construction + Title Number
Building foundation 31
版权声明
本文为[Xiaoxuzhu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210633381636.html
边栏推荐
- GeoServer 2.20.1 solving cross domain problems CORS
- php 文章关键字替换类
- 设置谷歌浏览器深色黑色背景
- 2021-10-17
- JSON编码解码
- 在Navicat工具中创建oracle数据库
- Unable to infer base url. This is common when using dynamic servlet registration or when the API is
- Use C # to connect with Hangao highgo database to obtain user data table name, table structure, table name and primary key
- leetcode 19.删除链表倒数的第N个节点
- VS2019官方的免费打印控件
猜你喜欢

在Navicat工具中创建oracle数据库

C#中listView列自动适应缩放的完美效果

Lecture de l'article: mesurer l'impact d'un accès DDOS réussi sur le comportement du client du serveur DNS géré

在vscode 中安装go插件并配置go环境以运行go

Studio3t 过期激活办法/以及重新设置使用日期的脚本不可用解决办法/Studio 3T无限激活原创

ReportViewer的RDLC打印报表怎么动态加载参数、图片、背景图

ELK日志分析系统的原理与介绍

C语言指针进阶(1.一阶与二阶指针)

GoLang学习资源清单

记录使用fastjson消息转换器遇到的问题和解决方法
随机推荐
playwright,selenium,操作ifram元素
Spawning Processes and Exec‘ing Processes
从零开始自制实现WebServer(十五)---- 日志库部分完结啦 实用小件DOUBLE-BUFFERING优化异步写入性能
论文阅读:Supporting Early and Scalable Discovery of Disinformation Websites
Leetcode 1387.将整数按权重排序(Sort Integers by The Power Value)
论文阅读:Analyzing Third Party Service Dependencies in Modern Web Services
delphi的json类:SuperObject,以及简单用法jsonHelper
Leetcode 1423.可获得的最大点数(Maximum Points You Can Obtain from Cards)
Leetcode 1557.可以到达所有点的最少点数目(Minimum Number of Vertices to Reach All Nodes)
VS2019官方的免费打印控件
Plsql14 software package download, localization and registration
标准函数返回值iResult
leetcode 209. 长度最小的子数组
OmniPlan工具使用手册
php 判断是不是同一个月
@Slf4j注解中 log 报错
leetcode 27.移除元素
UMLet初学者使用步骤
GoLang学习资源清单
leetcode 27. Removing Elements