『JavaSE』对象的比较

本篇博客介绍一下Java中对象的比较。

==和equals


我们知道Java中,对于引用类型来说,==比较的是两个对象的身份,使用equals才能比较两个对象的值

public class Test {
    public static void main(String[] args) {
        String str1 = new String("hello, world!");
        String str2 = new String("hello, world!");

        System.out.println("str1 == str2: " + (str1 == str2));
        System.out.println("str1.equals(str2): " + str1.equals(str2));
    }
}

在这里插入图片描述

我们定义一个自定义类型,我们使用equals进行比较来观察一下

class Fruit {
    public String name;
    public int price;

    public Fruit(String name, int price) {
        this.name = name;
        this.price = price;
    }
}

public class Test {
    public static void main(String[] args) {
        Fruit apple1 = new Fruit("apple", 10);
        Fruit apple2 = new Fruit("apple", 10);

        System.out.println("apple1 == apple2: " + (apple1 == apple2));
        System.out.println("apple1.equals(apple2): " + apple1.equals(apple2));
    }
}

在这里插入图片描述
可以看到,这里的==和equals结果都是false,不是说equals比较的是指,而apple1和apple2的值是相同的,为什么这里返回的还是false。
这是因为equals方法是Object的方法equals默认的比较方式就是对象身份的比较
在这里插入图片描述
如果我们想要实现值的比较,我们需要去覆写该方法

public class Test {
    public static void main(String[] args) {
        Fruit apple1 = new Fruit("apple", 10);
        Fruit apple2 = new Fruit("apple", 10);

        System.out.println("apple1 == apple2: " + (apple1 == apple2));
        System.out.println("apple1.equals(apple2): " + apple1.equals(apple2));
    }
}

class Fruit {
    public String name;
    public int price;

    public Fruit(String name, int price) {
        this.name = name;
        this.price = price;
    }

    @Override
    public boolean equals(Object o) {
        // 是同一个对象
        if (this == o) {
            return true;
        }

        // o为空或者o不是Fruit的实例
        if (o == null || !(o instanceof Fruit)) {
            return false;
        }

        Fruit fruit = (Fruit)o;
        return this.name.equals(fruit.name) && this.price == fruit.price;
    }
}

在这里插入图片描述
一般覆写equals的步骤大致如下

  • 如果两个引用指向同一个对象,返回true
  • 如果传入的引用为null,返回false
  • 如果传入的对象不是目标类型的实例,返回false
  • 按照类的实现目标完成比较

Comparable和Comparator


Comparable和Comparator都是用于比较数据的大小的,实现Comparable接口需要重写compareTo方法实现Comparator需要重写compare方法,这两个方法的返回值都是int,用int类型的值来确定比较结果。
我们来看一下Collections工具类中的两个sort方法,来简单理解一下二者的区别:
在这里插入图片描述
两个sort方法一个是只需要传入集合,但是要求集合中的元素实现了Comparable接口另一个不仅要传入一个集合,还需要传入一个Comparator对象,这里集合中的元素不需要实现Comparable接口
所以,我们可以大概能够想到二者的使用场景

  • 一个类在设计之初就有排序的需求,我们就可以选择实现Comparable接口
  • 如果是一个类在后期需要扩展或增加排序需求时,我们可以增加一个比较器Comparator

Comparable


我们来看一下使用Comparable实现水果按价钱排序

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        Fruit[] fruits = {
                new Fruit("peach", 30),
                new Fruit("apple", 10),
                new Fruit("banana", 50),
                new Fruit("pear", 20),
                new Fruit("berry", 40)
        };

        List<Fruit> fruitList = Arrays.asList(fruits);

        System.out.println(fruitList);
        Collections.sort(fruitList);
        System.out.println(fruitList);
    }
}

class Fruit implements Comparable<Fruit> {
    public String name;
    public int price;

    public Fruit(String name, int price) {
        this.name = name;
        this.price = price;
    }

    @Override
    public int compareTo(Fruit o) {
        return this.price - o.price;
    }

    @Override
    public String toString() {
        return "(" + this.name +
                ":" + this.price + ")";
    }
}

在这里插入图片描述

Comparator


我们来看一下使用Comparator实现水果按价钱排序

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        Fruit[] fruits = {
                new Fruit("peach", 30),
                new Fruit("apple", 10),
                new Fruit("banana", 50),
                new Fruit("pear", 20),
                new Fruit("berry", 40)
        };

        List<Fruit> fruitList = Arrays.asList(fruits);

        System.out.println(fruitList);
        Collections.sort(fruitList, new FruitComparator());
        System.out.println(fruitList);
    }
}

class Fruit {
    public String name;
    public int price;

    public Fruit(String name, int price) {
        this.name = name;
        this.price = price;
    }

    @Override
    public String toString() {
        return "(" + this.name +
                ":" + this.price + ")";
    }
}

class FruitComparator implements Comparator<Fruit> {
    @Override
    public int compare(Fruit o1, Fruit o2) {
        return o1.price - o2.price;
    }
}

在这里插入图片描述
我们还有一种更简单的写法,如下:

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        Fruit[] fruits = {
                new Fruit("peach", 30),
                new Fruit("apple", 10),
                new Fruit("banana", 50),
                new Fruit("pear", 20),
                new Fruit("berry", 40)
        };

        List<Fruit> fruitList = Arrays.asList(fruits);

        System.out.println(fruitList);
        Collections.sort(fruitList, new Comparator<Fruit>() {
            @Override
            public int compare(Fruit o1, Fruit o2) {
                return o1.price - o2.price;
            }
        });
        System.out.println(fruitList);
    }
}

class Fruit {
    public String name;
    public int price;

    public Fruit(String name, int price) {
        this.name = name;
        this.price = price;
    }

    @Override
    public String toString() {
        return "(" + this.name +
                ":" + this.price + ")";
    }
}

在这里插入图片描述

和Java集合框架的配合


  • 使用contains类似的方法内部基本在调用元素的equals方法,所以要求元素覆写过equals方法;
  • 使用HashMap,key的比较内部会调用equals方法,所以要求元素覆写过equals方法;
  • 使用排序相关方法,内部需要进行排序,所以可以选择实现Comparable接口或者传入一个Comparator对象
  • 使用TreeMap,key需要进行大小比较,所以可以选择实现Comparable接口或者传入一个Comparator对象
  • 等等。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值