当前位置:网站首页>近期学习遇到的比较问题
近期学习遇到的比较问题
2022-06-30 09:33:00 【王小小鸭】
做题遇到了一些比较的内容,来做一些总结
compareTo比较方法
例题是:
定义一个接口用来实现两个对象的比较。
interface CompareObject{
public int compareTo(Object o); //若返回值是 0 , 代表相等; 若为正数,代表当前对象大;负数代表当前对象小
}
定义一个Circle类,声明redius属性,提供getter和setter方法
定义一个ComparableCircle类,继承Circle类并且实现CompareObject接口。在ComparableCircle类中给出接口中方法compareTo的实现体,用来比较两个圆的半径大小。
定义一个测试类InterfaceTest,创建两个ComparableCircle对象,调用compareTo方法比较两个类的半径大小。
代码如下:
- 接口CompareObject(定义一个比较方法compareTo):
package com.object_04.interface_05;
public interface CompareObject {
public int compareTo(Object o);
//若返回值是 0 , 代表相等; 若为正数,代表当前对象大;负数代表当前对象小
}
- 定义一个Circle类
package com.object_04.interface_05;
//定义一个Circle类
public class Circle {
private double redius; //定义一个半径
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("半径为:"+redius);
return 0;
}
}
- 定义一个ComparableCircle类
- 重写是能否比较成功的重中之重,这里有一个重要的点,就是进行 this.getRedius() 与 ((Circle) o).getRedius() 比较时一定要有返回值,才能在测试类打印时输出对应结果
package com.object_04.interface_05;
//定义一个ComparableCircle类,继承Circle类并且实现CompareObject接口。
// 在ComparableCircle类中给出接口中方法compareTo的实现体,用来比较两个圆的半径大小
public class ComparableCircle extends Circle implements CompareObject {
public ComparableCircle() {
}
public ComparableCircle(double redius) {
super(redius);
}
@Override //重写比较方法
public int compareTo(Object o) {
// 运算符预判
if (o instanceof Circle){
//如果不进行预判出现ClassCastException 类转换异常
// 然后进行比较
if(this.getRedius() == ((Circle) o).getRedius()){
return 0;
}else if(this.getRedius() < ((Circle) o).getRedius()){
return -1;
}else {
return 1;
}
}
return 2;
}
}
- 测试类
```java
- package com.object_04.interface_05;
public class InterfaceTest {
public static void main(String[] args) {
CompareObject c1 = new ComparableCircle(10);
// 可以使用多态和本态,优先使用多态(站高望远)
CompareObject c2 = new ComparableCircle(20);
int compRs = c1.compareTo(c2);
System.out.println(compRs);
switch (compRs) {
case 0:
System.out.println("相等");
break;
case 1:
System.out.println("左边大");
break;
case -1:
System.out.println("右边大");
break;
default:
break;
}
}
}

另外一个做练习遇到的比较是:
编写工资系统,实现不同类型员工(多态)的按月发放工资。如果当月出现某个
Employee对象的生日,则将该雇员的工资增加100元。
实验说明:
(1)定义一个Employee类,该类包含:
private成员变量name,number,birthday,其中birthday 为MyDate类的对象;
abstract方法earnings();
toString()方法输出对象的name,number和birthday。
(2)MyDate类包含:
private成员变量year,month,day ;
toDateString()方法返回日期对应的字符串:xxxx年xx月xx日
(3)定义SalariedEmployee类继承Employee类,实现按月计算工资的员工处
理。该类包括:private成员变量monthlySalary;
实现父类的抽象方法earnings(),该方法返回monthlySalary值;toString()方法输
出员工类型信息及员工的name,number,birthday。
(4)参照SalariedEmployee类定义HourlyEmployee类,实现按小时计算工资的员工处理。该类包括:
private成员变量wage和hour;
实现父类的抽象方法earnings(),该方法返回wage*hour值;
toString()方法输出员工类型信息及员工的name,number,birthday。
(5)定义PayrollSystem类,创建Employee变量数组并初始化,该数组存放各类雇员对象的引用。利用循环结构遍历数组元素,输出各个对象的类型,name,number,birthday,以及该对象生日。当键盘输入本月月份值时,如果本月是某个Employee对象的生日,还要输出增加工资信息。
- 创建Employee类(员工类)
package com.object_04.interface_04;
//创建Employee类
public abstract class Employee {
//姓名
private String name;
//工号
private String num;
//生日
private MyDate birthday;
//构造方法
public Employee(String name, String num, MyDate birthday) {
this.name = name;
this.num = num;
this.birthday = birthday;
}
//无参构造 不写也行
public Employee() {
}
//抽象类方法
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);
}
- 创建员工工资类SalariedEmployee
package com.object_04.interface_04;
public class SalariedEmployee extends Employee{
//正式员工 按每月发工资
private double monthlySalary;
public SalariedEmployee(){
}
public SalariedEmployee(String name, String num, MyDate birthday, double monthlySalary){
super(name, num, birthday);
this.monthlySalary = monthlySalary;
}
//重写父类Employee的earnings()方法
@Override
public double earnings() {
return monthlySalary;
}
@Override
public String toString() {
return super.toString() + ",薪水:"+this.earnings();
}
@Override
public MyDate getBirthdayElement(int i) {
return null;
}
}
- 小时工资HourlyEmployee
package com.object_04.interface_04;
//小时工 按小时结算工资
public class HourlyEmployee extends Employee{
//每小时的工资
private double wage;
//时间
private double hour;
public HourlyEmployee(String name, String num, MyDate birthday, double wage, double hour){
//super继承父类
super(name, num, birthday);
this.wage = wage;
this.hour = hour;
}
public HourlyEmployee(String 涂安丽, int i, com.object_04.interface_04.MyDate myDate, int wage, int hour) {
}
//重写父类Employee的earnings()方法
@Override
public double earnings() {
return wage * hour;
}
@Override
public String toString() {
return super.toString()+this.earnings();
}
@Override
public MyDate getBirthdayElement(int i) {
return null;
}
}
- 工资系统类
import java.util.Arrays;
//工资系统类
public class PayrollSystem {
//创建数组 用于存储员工信息
private Employee[] employees;
public PayrollSystem(){
}
@Override
public String toString() {
return Arrays.toString(employees);
}
//有参构造
public PayrollSystem(Employee[] employees){
this.employees = employees;
}
//获取数组
public Employee[] getEmployees() {
return employees;
}
//更改数组
public void setEmployees(Employee[] employees) {
this.employees = employees;
}
}
- 测试类
package com.object_04.interface_04;
import java.util.Scanner;
public class EmployeeTest {
public static void main(String[] args) {
//创建一个PayrollSystem好比创建一个财务系统
//用于存储员工信息
PayrollSystem payrollSystem = new PayrollSystem();
MyDate e1B = new MyDate(2000,10,1);
Employee e1 = new SalariedEmployee("张三","A001",e1B,5000.0);
Employee e2 = new SalariedEmployee("李四","A002",e1B,5000.0);
//创建数组 给它赋值 将他赋给payroSystem的数组赋值
Employee[] employees = {
e1,e2};
//将他赋给payrollSystem的数组
payrollSystem.setEmployees(employees);
Scanner scanner = new Scanner(System.in);
while (true){
System.out.println("功能列表:" +
"1、列出员工信息" +
"2、输入月份" +
"3、退出");
System.out.print("请输入要执行的命令:");
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){
//增加员工
System.out.print("请输入月份:");
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()+"该月生日,奖励100元");
}else{
continue;
}
}
}
}
}
}


equals() 方法
String 类中重写了 equals() 方法用于比较两个字符串的内容是否相等。
语法
public boolean equals(Object anObject)
参数
返回值
如果给定对象与字符串相等,则返回 true;否则返回 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("返回值 = " + retVal );
retVal = Str1.equals( Str3 );
System.out.println("返回值 = " + retVal );
}
}
以上程序执行结果为:
返回值 = true
返回值 = true
详情可见:Java String equals() 方法 | 菜鸟教程 (runoob.com)
关于java中常见比较方法更多可以看(88条消息) Java的比较方法_m0_67351863的博客-CSDN博客_java 比较
边栏推荐
- Acquisition de 100% des actions de Guilin latex par Guilin Robust Medical pour combler le vide de la gamme de produits Latex
- Interviewer: do you understand the principle of recyclerview layout animation?
- DataTableToModelList实体类
- 仿照微信Oauth2.0接入方案
- Understanding of MVVM and MVC
- What kind of experience is it to develop a "grandson" who will call himself "Grandpa"?
- Application of hongruan face recognition
- Self service terminal handwritten Chinese character recognition input method library tjfink introduction
- List set export excel table
- Net framework system requirements
猜你喜欢

Linear-gradient()

Handwriting sorter component

Abstract factory pattern

JVM garbage collector G1 & ZGC details

Express file upload

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

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

Duplicate entry '2' for key 'primary appears in JPA‘

JVM tuning tool commands (notes)

4. use ibinder interface flexibly for short-range communication
随机推荐
Self service terminal development process
2021-10-20
Duplicate entry '2' for key 'primary appears in JPA‘
Cftpconnection:: getfile() download FTP server files and related parameter descriptions
MySQL knowledge summary (useful for thieves)
Coredata acquisition in swift sorting, ascending, descending
POJ 1753 flip game (DFS 𞓜 bit operation)
DDD interview
12. problem set: process, thread and JNI architecture
仿照微信Oauth2.0接入方案
Why won't gold depreciate???
Function simplification principle: save if you can
Ocx control can be called by IE on some computers, but can not be called by IE on some computers
Reading notes of "Introduction to deep learning: pytoch"
Installation, use and explanation of vulnerability scanning tool OpenVAS
OCX child thread cannot trigger event event (forward)
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!
Pipe pipe --namedpipe and anonymouspipe
How do I start? (continuously updating)
(zero) most complete JVM knowledge points