当前位置:网站首页>Comparison problems encountered in recent study
Comparison problems encountered in recent study
2022-06-30 09:40:00 【Wang Xiaoya】
I met some comparative content when I was doing the title , To make a summary
compareTo Comparison method
The example is :
Define an interface to compare two objects .
interface CompareObject{
public int compareTo(Object o); // If the return value is 0 , For equality ; If it's a positive number , Represents the size of the current object ; A negative number indicates that the current object is small
}
Define a Circle class , Statement redius attribute , Provide getter and setter Method
Define a ComparableCircle class , Inherit Circle Class and implement CompareObject Interface . stay ComparableCircle The methods in the interface are given in the class compareTo Implementation of , Used to compare the radius of two circles .
Define a test class InterfaceTest, Create two ComparableCircle object , call compareTo Method to compare the radius of two classes .
The code is as follows :
- Interface CompareObject( Define a comparison method compareTo):
package com.object_04.interface_05;
public interface CompareObject {
public int compareTo(Object o);
// If the return value is 0 , For equality ; If it's a positive number , Represents the size of the current object ; A negative number indicates that the current object is small
}
- Define a Circle class
package com.object_04.interface_05;
// Define a Circle class
public class Circle {
private double redius; // Define a radius
public Circle() {
}
public Circle(double redius) {
this.redius = redius;
}
public double getRedius() {
return redius;
}
public void setRedius(double redius) {
this.redius = redius;
}
public int compareTo(Object o) {
System.out.println(" The radius is :"+redius);
return 0;
}
}
- Define a ComparableCircle class
- Rewriting is the top priority for success , Here's an important point , Is to this.getRedius() And ((Circle) o).getRedius() There must be a return value when comparing , The corresponding results can be output when the test class is printed
package com.object_04.interface_05;
// Define a ComparableCircle class , Inherit Circle Class and implement CompareObject Interface .
// stay ComparableCircle The methods in the interface are given in the class compareTo Implementation of , Used to compare the radius of two circles
public class ComparableCircle extends Circle implements CompareObject {
public ComparableCircle() {
}
public ComparableCircle(double redius) {
super(redius);
}
@Override // Rewrite the comparison method
public int compareTo(Object o) {
// Operator prediction
if (o instanceof Circle){
// If you don't predict, there will be ClassCastException Class conversion exception
// And then compare them
if(this.getRedius() == ((Circle) o).getRedius()){
return 0;
}else if(this.getRedius() < ((Circle) o).getRedius()){
return -1;
}else {
return 1;
}
}
return 2;
}
}
- Test class
```java
- package com.object_04.interface_05;
public class InterfaceTest {
public static void main(String[] args) {
CompareObject c1 = new ComparableCircle(10);
// Polymorphic and native states can be used , Use polymorphism first ( Stand high and look far )
CompareObject c2 = new ComparableCircle(20);
int compRs = c1.compareTo(c2);
System.out.println(compRs);
switch (compRs) {
case 0:
System.out.println(" equal ");
break;
case 1:
System.out.println(" Left large ");
break;
case -1:
System.out.println(" Big on the right ");
break;
default:
break;
}
}
}

Another comparison of doing exercises is :
Write salary system , Realize different types of employees ( polymorphic ) The salary is paid on a monthly basis . If a certain... Occurs in the current month
Employee Object's birthday , The employee's salary will be increased 100 element .
Experimental instructions :
(1) Define a Employee class , This class contains :
private Member variables name,number,birthday, among birthday by MyDate Class object ;
abstract Method earnings();
toString() Method outputs the name of the object name,number and birthday.
(2)MyDate Class inclusion :
private Member variables year,month,day ;
toDateString() Method returns the string corresponding to the date :xxxx year xx month xx Japan
(3) Definition SalariedEmployee Class inheritance Employee class , Employees who are paid on a monthly basis
The reason is . This category includes :private Member variables monthlySalary;
Abstract methods that implement the parent class earnings(), This method returns monthlySalary value ;toString() Method input
Give the employee type information and employee's information name,number,birthday.
(4) reference SalariedEmployee Class definition HourlyEmployee class , Realize the processing of employees whose wages are calculated by hour . This category includes :
private Member variables wage and hour;
Abstract methods that implement the parent class earnings(), This method returns wage*hour value ;
toString() Method to output employee type information and employee information name,number,birthday.
(5) Definition PayrollSystem class , establish Employee Variable array and initialize , This array stores references to various employee objects . Use the loop structure to traverse the array elements , Output the type of each object ,name,number,birthday, And the object's birthday . When the current month value is entered on the keyboard , If this month is a Employee Object's birthday , Also output salary increase information .
- establish Employee class ( The employee class )
package com.object_04.interface_04;
// establish Employee class
public abstract class Employee {
// full name
private String name;
// Job number
private String num;
// Birthday
private MyDate birthday;
// Construction method
public Employee(String name, String num, MyDate birthday) {
this.name = name;
this.num = num;
this.birthday = birthday;
}
// No arguments structure It's OK not to write
public Employee() {
}
// Abstract class methods
public abstract double earnings();
@Override
public String toString() {
return "name:" + name + ",num:" + num + ",birthday:" + birthday;
}
public MyDate getBirthday() {
return birthday;
}
public String getName() {
return name;
}
public abstract MyDate getBirthdayElement(int i);
}
- Create employee salary category SalariedEmployee
package com.object_04.interface_04;
public class SalariedEmployee extends Employee{
// regular employee Pay monthly salary
private double monthlySalary;
public SalariedEmployee(){
}
public SalariedEmployee(String name, String num, MyDate birthday, double monthlySalary){
super(name, num, birthday);
this.monthlySalary = monthlySalary;
}
// Override parent class Employee Of earnings() Method
@Override
public double earnings() {
return monthlySalary;
}
@Override
public String toString() {
return super.toString() + ", salary :"+this.earnings();
}
@Override
public MyDate getBirthdayElement(int i) {
return null;
}
}
- Hourly wage HourlyEmployee
package com.object_04.interface_04;
// Hourly work Pay by hour
public class HourlyEmployee extends Employee{
// Hourly wage
private double wage;
// Time
private double hour;
public HourlyEmployee(String name, String num, MyDate birthday, double wage, double hour){
//super Inherited parent class
super(name, num, birthday);
this.wage = wage;
this.hour = hour;
}
public HourlyEmployee(String Tu Anli , int i, com.object_04.interface_04.MyDate myDate, int wage, int hour) {
}
// Override parent class Employee Of earnings() Method
@Override
public double earnings() {
return wage * hour;
}
@Override
public String toString() {
return super.toString()+this.earnings();
}
@Override
public MyDate getBirthdayElement(int i) {
return null;
}
}
- Payroll system
import java.util.Arrays;
// Payroll system
public class PayrollSystem {
// Create array Used to store employee information
private Employee[] employees;
public PayrollSystem(){
}
@Override
public String toString() {
return Arrays.toString(employees);
}
// There are parametric structures
public PayrollSystem(Employee[] employees){
this.employees = employees;
}
// Get array
public Employee[] getEmployees() {
return employees;
}
// Change array
public void setEmployees(Employee[] employees) {
this.employees = employees;
}
}
- Test class
package com.object_04.interface_04;
import java.util.Scanner;
public class EmployeeTest {
public static void main(String[] args) {
// Create a PayrollSystem It's like creating a financial system
// Used to store employee information
PayrollSystem payrollSystem = new PayrollSystem();
MyDate e1B = new MyDate(2000,10,1);
Employee e1 = new SalariedEmployee(" Zhang San ","A001",e1B,5000.0);
Employee e2 = new SalariedEmployee(" Li Si ","A002",e1B,5000.0);
// Create array Give it a value Give him to payroSystem Array assignment of
Employee[] employees = {
e1,e2};
// Give him to payrollSystem Array of
payrollSystem.setEmployees(employees);
Scanner scanner = new Scanner(System.in);
while (true){
System.out.println(" Function list :" +
"1、 List employee information " +
"2、 Enter month " +
"3、 sign out ");
System.out.print(" Please enter the command to execute :");
int s1 = scanner.nextInt();
if(s1 == 1){
for (int i = 0;i<employees.length;i++){
System.out.println(employees[i]);
}
}else if(s1 == 3){
return;
}else if(s1 == 2){
// Increase staff
System.out.print(" Please enter the month :");
int s2 = scanner.nextInt();
for(int i = 0;i < payrollSystem.getEmployees().length;i++){
System.out.println(employees[i]);
System.out.println(employees[i].getBirthday());
System.out.println(employees[i].getBirthday().getMonth());
if(employees[i].getBirthday().getMonth()==(s2)){
System.out.println(employees[i].getName()+" Birthday of the month , Reward 100 element ");
}else{
continue;
}
}
}
}
}
}


equals() Method
String class equals() Method is used to compare whether the contents of two strings are equal .
grammar
public boolean equals(Object anObject)
Parameters
Return value
If the given object is equal to a string , Then return to true; Otherwise return to false.
public class Test {
public static void main(String args[]) {
String Str1 = new String("runoob");
String Str2 = Str1;
String Str3 = new String("runoob");
boolean retVal;
retVal = Str1.equals( Str2 );
System.out.println(" Return value = " + retVal );
retVal = Str1.equals( Str3 );
System.out.println(" Return value = " + retVal );
}
}
The execution result of the above procedure is :
Return value = true
Return value = true
Details visible :Java String equals() Method | Novice tutorial (runoob.com)
About java More common comparison methods in (88 Bar message ) Java The comparison method of _m0_67351863 The blog of -CSDN Blog _java Compare
边栏推荐
- What is the difference between ZigBee, Bluetooth and WiFi (copy and reprint)
- QR code generation and analysis
- Pytorch graduate warm LR installation
- Experience of an acmer
- JVM garbage collector G1 & ZGC details
- 单片机 MCU 固件打包脚本软件
- Cb/s Architecture - Implementation Based on cef3+mfc
- What are the SQL add / delete / modify queries?
- MySQL internal component structure
- Pipe pipe --namedpipe and anonymouspipe
猜你喜欢

云技能提升好伙伴,亚马逊云师兄今天正式营业

Summary of Android knowledge points and common interview questions

7. know JNI and NDK

Electron, which can wrap web page programs into desktop applications

oracle跨数据库复制数据表-dblink

Agp7.0|kts makes a reinforced plug-in

Express の post request

MySQL优化

Self service terminal handwritten Chinese character recognition input method library tjfink introduction

Flutter 中的 ValueNotifier 和 ValueListenableBuilder
随机推荐
Idea shortcut key settings
Flutter 中的 ValueNotifier 和 ValueListenableBuilder
MySQL index optimization miscellaneous
Dart basic notes
Notes on masking and padding in tensorflow keras
Recommend a very easy-to-use network communication framework HP socket
Guilin robust medical acquired 100% equity of Guilin Latex to fill the blank of latex product line
Acquisition de 100% des actions de Guilin latex par Guilin Robust Medical pour combler le vide de la gamme de produits Latex
Differences between the notify(), notifyall(), notifydatasetchanged(), notifydatasetinvalidated() methods in the adapter
Pytorch for former Torch users - Tensors
训练一个图像分类器demo in PyTorch【学习笔记】
Niuke walks on the tree (ingenious application of parallel search)
Tclistener server and tcpclient client
Applet learning path 2 - event binding
Application of hongruan face recognition
直播带货源码开发中,如何降低直播中的延迟?
Self service terminal handwritten Chinese character recognition input method library tjfink introduction
Electron, which can wrap web page programs into desktop applications
11.自定义hooks
thrift简单使用