当前位置:网站首页>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
边栏推荐
- DataTableToModelList实体类
- Summary of Android knowledge points and common interview questions
- Pit encountered by fastjason
- Redis docker 主从模式与哨兵sentinel
- (zero) most complete JVM knowledge points
- thrift简单使用
- 【Ubuntu-MySQL8安装与主从复制】
- 5. Messager framework and imessager interface
- Numpy (time date and time increment)
- ACM intensive training graph theory exercise 3 in the summer vacation of 2020 [problem solving]
猜你喜欢

MySQL internal component structure

So the toolbar can still be used like this? The toolbar uses the most complete parsing. Netizen: finally, you don't have to always customize the title bar!

桂林 穩健醫療收購桂林乳膠100%股權 填補乳膠產品線空白

Guilin robust medical acquired 100% equity of Guilin Latex to fill the blank of latex product line

Small program learning path 1 - getting to know small programs

(zero) most complete JVM knowledge points

MySQL-- Entity Framework Code First(EF Code First)

近期学习遇到的比较问题

Distributed ID

What kind of experience is it to develop a "grandson" who will call himself "Grandpa"?
随机推荐
MySQL index and data storage structure foundation
ES6 learning path (II) let & const
小程序手持弹幕的原理及实现(uni-app)
Pit encountered by fastjason
Mysq database remote connection error, remote connection is not allowed
八大排序(一)
ES6 learning path (IV) operator extension
Express - static resource request
I'm late for school
桂林 稳健医疗收购桂林乳胶100%股权 填补乳胶产品线空白
Niuke IOI weekly competition 20 popularization group (problem solving)
The elegant combination of walle and Jianbao
ABAP-时间函数
Create thread pool demo
Initialize static resource demo
【新书推荐】MongoDB Performance Tuning
MySQL explain
Self service terminal handwritten Chinese character recognition input method library tjfink introduction
Baidu map JS browsing terminal
Self service terminal development process