百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程字典 > 正文

Java 对象排序详解

toyiye 2024-05-25 20:11 12 浏览 0 评论

很难想象有Java开发人员不曾使用过Collection框架。在Collection框架中,主要使用的类是来自List接口中的ArrayList,以及来自Set接口的HashSet、TreeSet,我们经常处理这些Collections的排序。

在本文中,我将主要关注排序Collection的ArrayList、HashSet、TreeSet,以及最后但并非最不重要的数组。

让我们看看如何对给定的整数集合(5,10,0,-1)进行排序:

数据(整数)存储在ArrayList中

private void sortNumbersInArrayList() {

List<Integer> integers = new ArrayList<>();

integers.add(5);

integers.add(10);

integers.add(0);

integers.add(-1);

System.out.println("Original list: " +integers);

Collections.sort(integers);

System.out.println("Sorted list: "+integers);

Collections.sort(integers, Collections.reverseOrder());

System.out.println("Reversed List: " +integers);

}

输出:

Original list: [5, 10, 0, -1]

Sorted list: [-1, 0, 5, 10]

Reversed List: [10, 5, 0, -1]

数据(整数)存储在HashSet中

private void sortNumbersInHashSet() {

Set<Integer> integers = new HashSet<>();

integers.add(5);

integers.add(10);

integers.add(0);

integers.add(-1);

System.out.println("Original set: " +integers);

// Collections.sort(integers); This throws error since sort method accepts list not collection

List list = new ArrayList(integers);

Collections.sort(list);

System.out.println("Sorted set: "+list);

Collections.sort(list, Collections.reverseOrder());

System.out.println("Reversed set: " +list);

}

输出:

Original set: [0, -1, 5, 10]

Sorted set: [-1, 0, 5, 10]

Reversed set: [10, 5, 0, -1]

在这个例子中(数据(整数)存储在HashSet中),我们看到HashSet被转换为ArrayList进行排序。在不转换为ArrayList的情况下,可以通过使用TreeSet来实现排序。TreeSet是Set的另一个实现,并且在使用默认构造函数创建Set时,使用自然排序进行排序。

数据(整数)存储在TreeSet中

private void sortNumbersInTreeSet() {

Set<Integer> integers = new TreeSet<>();

integers.add(5);

integers.add(10);

integers.add(0);

integers.add(-1);

System.out.println("Original set: " + integers);

System.out.println("Sorted set: "+ integers);

Set<Integer> reversedIntegers = new TreeSet(Collections.reverseOrder());

reversedIntegers.add(5);

reversedIntegers.add(10);

reversedIntegers.add(0);

reversedIntegers.add(-1);

System.out.println("Reversed set: " + reversedIntegers);

}

输出:

Original set: [-1, 0, 5, 10]

Sorted set: [-1, 0, 5, 10]

Reversed set: [10, 5, 0, -1]

在这种情况下,“Original set:”和“Sorted set:”两者相同,因为我们已经使用了按排序顺序存储数据的TreeSet,所以在插入后不用排序。

到目前为止,一切都如期工作,排序似乎是一件轻而易举的事。现在让我们尝试在各个Collection中存储自定义对象(比如Student),并查看排序是如何工作的。

数据(Student对象)存储在ArrayList中

private void sortStudentInArrayList() {

List<Student> students = new ArrayList<>();

Student student1 = createStudent("Biplab", 3);

students.add(student1);

Student student2 = createStudent("John", 1);

students.add(student2);

Student student3 = createStudent("Pal", 5);

students.add(student3);

Student student4 = createStudent("Biplab", 2);

students.add(student4);

System.out.println("Original students list: " + students);

Collections.sort(students);// Error here

System.out.println("Sorted students list: " + students);

Collections.sort(students, Collections.reverseOrder());

System.out.println("Reversed students list: " + students);

}

private Student createStudent(String name, int no) {

Student student = new Student();

student.setName(name);

student.setNo(no);

return student;

}

public class Student {

String name;

int no;

public String getName() {

return name;

}

public int getNo() {

return no;

}

public void setName(String name) {

this.name = name;

}

public void setNo(int no) {

this.no = no;

}

@Override

public String toString() {

return "Student{" +

"name='" + name + '\'' +

", no=" + no +

'}';

}

}

这会抛出编译时错误,并显示以下错误消息:

sort(java.util.List<T>)

in Collections cannot be applied

to (java.util.List<com.example.demo.dto.Student>)

reason: no instance(s) of type variable(s) T exist so that Student

conforms to Comparable<? Super T>

为了解决这个问题,要么Student类需要实现Comparable,要么需要在调用Collections.sort时传递Comparator对象。在整型情况下,排序方法没有错误,因为Integer类实现了Comparable。让我们看看,实现Comparable或传递Comparator如何解决这个问题,以及排序方法如何实现Collection排序。

使用Comparable排序

package com.example.demo.dto;

public class Student implements Comparable{

String name;

int no;

public String getName() {

return name;

}

public int getNo() {

return no;

}

public void setName(String name) {

this.name = name;

}

public void setNo(int no) {

this.no = no;

}

@Override

public String toString() {

return "Student{" +

"name='" + name + '\'' +

", no=" + no +

'}';

}

@Override

public int compareTo(Object o) {

return this.getName().compareTo(((Student) o).getName());

}

}

输出:

Original students list: [Student{name='Biplab', no=3}, Student{name='John', no=1}, Student{name='Pal', no=5}, Student{name='Biplab', no=2}]

Sorted students list: [Student{name='Biplab', no=3}, Student{name='Biplab', no=2}, Student{name='John', no=1}, Student{name='Pal', no=5}]

Reversed students list: [Student{name='Pal', no=5}, Student{name='John', no=1}, Student{name='Biplab', no=3}, Student{name='Biplab', no=2}]

在所有示例中,为了颠倒顺序,我们使用“Collections.sort(students, Collections.reverseOrder()”,相反的,它可以通过改变compareTo(..)方法的实现而达成目标,且compareTo(…) 的实现看起来像这样 :

@Override

public int compareTo(Object o) {

return (((Student) o).getName()).compareTo(this.getName());

}

输出:

Original students list: [Student{name='Biplab', no=3}, Student{name='John', no=1}, Student{name='Pal', no=5}, Student{name='Biplab', no=2}]

Sorted students list: [Student{name='Pal', no=5}, Student{name='John', no=1}, Student{name='Biplab', no=3}, Student{name='Biplab', no=2}]

Reversed students list: [Student{name='Biplab', no=3}, Student{name='Biplab', no=2}, Student{name='John', no=1}, Student{name='Pal', no=5}]

如果我们观察输出结果,我们可以看到“Sorted students list:”以颠倒的顺序(按学生name)输出学生信息。

到目前为止,对学生的排序是根据学生的“name”而非“no”来完成的。如果我们想按“no”排序,我们只需要更改Student类的compareTo(Object o)实现,如下所示:

@Override

public int compareTo(Object o) {

return (this.getNo() < ((Student) o).getNo() ? -1 : (this.getNo() == ((Student) o).getNo() ? 0 : 1));

}

输出:

Original students list: [Student{name='Biplab', no=3}, Student{name='John', no=1}, Student{name='Pal', no=5}, Student{name='Biplab', no=2}]

Sorted students list: [Student{name='John', no=1}, Student{name='Biplab', no=2}, Student{name='Biplab', no=3}, Student{name='Pal', no=5}]

Reversed students list: [Student{name='Pal', no=5}, Student{name='Biplab', no=3}, Student{name='Biplab', no=2}, Student{name='John', no=1}]

在上面的输出中,我们可以看到“no”2和3的两名学生具有相同的名字“Biplab”。

现在假设我们首先需要按“name”对这些学生进行排序,如果超过1名学生具有相同姓名的话,则这些学生需要按“no”排序。为了实现这一点,我们需要改变compareTo(…)方法的实现,如下所示:

@Override

public int compareTo(Object o) {

int result = this.getName().compareTo(((Student) o).getName());

if(result == 0) {

result = (this.getNo() < ((Student) o).getNo() ? -1 : (this.getNo() == ((Student) o).getNo() ? 0 : 1));

}

return result;

}

输出:

Original students list: [Student{name='Biplab', no=3}, Student{name='John', no=1}, Student{name='Pal', no=5}, Student{name='Biplab', no=2}]

Sorted students list: [Student{name='Biplab', no=2}, Student{name='Biplab', no=3}, Student{name='John', no=1}, Student{name='Pal', no=5}]

Reversed students list: [Student{name='Pal', no=5}, Student{name='John', no=1}, Student{name='Biplab', no=3}, Student{name='Biplab', no=2}]

使用Comparator排序

为了按照“name”对Students进行排序,我们将添加一个Comparator并将其传递给排序方法:

public class Sorting {

private void sortStudentInArrayList() {

List<Student> students = new ArrayList<>();

Student student1 = createStudent("Biplab", 3);

students.add(student1);

Student student2 = createStudent("John", 1);

students.add(student2);

Student student3 = createStudent("Pal", 5);

students.add(student3);

Student student4 = createStudent("Biplab", 2);

students.add(student4);

System.out.println("Original students list: " + students);

Collections.sort(integers, new NameComparator());

System.out.println("Sorted students list: " + students);

}

}

public class Student {

String name;

int no;

public String getName() {

return name;

}

public int getNo() {

return no;

}

public void setName(String name) {

this.name = name;

}

public void setNo(int no) {

this.no = no;

}

@Override

public String toString() {

return "Student{" +

"name='" + name + '\'' +

", no=" + no +

'}';

}

}

class NameComparator implements Comparator<Student> {

@Override

public int compare(Student o1, Student o2) {

return o1.getName().compareTo(o2.getName());

}

}

输出:

Original students list: [Student{name='Biplab', no=3}, Student{name='John', no=1}, Student{name='Pal', no=5}, Student{name='Biplab', no=2}]

Sorted students list: [Student{name='Biplab', no=3}, Student{name='Biplab', no=2}, Student{name='John', no=1}, Student{name='Pal', no=5}]

同样,如果我们想按照“no”对Students排序,那么可以再添加一个Comparator(NoComparator.java),并将其传递给排序方法,然后数据将按“no”排序。

现在,如果我们想通过“name”然后“no”对学生进行排序,那么可以在compare(…)内结合两种逻辑来实现。

class NameNoComparator implements Comparator<Student> {

@Override

public int compare(Student o1, Student o2) {

int result = o1.getName().compareTo(o2.getName());

if(result == 0) {

result = o1.getNo() < o2.getNo() ? -1 : o1.getNo() == o2.getNo() ? 0 : 1;

}

return result;

}

}

输出:

Original students list: [Student{name='Biplab', no=3}, Student{name='John', no=1}, Student{name='Pal', no=5}, Student{name='Biplab', no=2}]

Sorted students list: [Student{name='Biplab', no=2}, Student{name='Biplab', no=3}, Student{name='John', no=1}, Student{name='Pal', no=5}]

数据(Students对象)存储在Set中

在Set的这个情况下,我们需要将HashSet转换为ArrayList,或使用TreeSet对数据进行排序。此外,我们知道要使Set工作,equals(…)和hashCode()方法需要被覆盖。下面是基于“no”字段覆盖equals和hashcode的例子,且这些是IDE自动生成的代码。与Comparable或Comparator相关的其他代码与ArrayList相同。

@Override

public boolean equals(Object o) {

if (this == o) return true;

if (o == null || getClass() != o.getClass()) return false;

Student student = (Student) o;

return no == student.no;

}

@Override

public int hashCode() {

return Objects.hash(no);

}

数据(Students对象)存储在数组中

为了对数组排序,我们需要做与排序ArrayList相同的事情(要么执行Comparable要么传递Comparable给sort方法)。在这种情况下,sort方法是“Arrays.sort(Object[] a )”而非“Collections.sort(..)”。

private void sortStudentInArray() {

Student [] students = new Student[4];

Student student1 = createStudent("Biplab", 3);

students[0] = student1;

Student student2 = createStudent("John", 1);

students[1] = student2;

Student student3 = createStudent("Pal", 5);

students[2] = student3;

Student student4 = createStudent("Biplab", 2);

students[3] = student4;

System.out.print("Original students list: ");

for (Student student: students) {

System.out.print( student + " ,");

}

Arrays.sort(students);

System.out.print("\nSorted students list: ");

for (Student student: students) {

System.out.print( student +" ,");

}

Arrays.sort(students, Collections.reverseOrder());

System.out.print("\nReversed students list: " );

for (Student student: students) {

System.out.print( student +" ,");

}

}

//Student class

// All properties goes here

@Override

public int compareTo(Object o) {

int result =this.getName().compareTo(((Student)o).getName());

if(result ==0) {

result = (this.getNo() < ((Student) o).getNo() ? -1 : (this.getNo() == ((Student) o).getNo() ? 0 : 1));

}

return result;

}

输出:

Original students list: Student{name='Biplab', no=3} ,Student{name='John', no=1} ,Student{name='Pal', no=5} ,Student{name='Biplab', no=2} ,

Sorted students list: Student{name='Biplab', no=2} ,Student{name='Biplab', no=3} ,Student{name='John', no=1} ,Student{name='Pal', no=5} ,

Reversed students list: Student{name='Pal', no=5} ,Student{name='John', no=1} ,Student{name='Biplab', no=3} ,Student{name='Biplab', no=2} ,

结论

我们经常对Comparable/Comparator的使用以及何时使用哪个感到困惑。下面是我总结的Comparable/Comparator的使用场景。

Comparator:

  • 当我们想排序一个无法修改的类的实例时。例如来自jar的类的实例。
  • 根据用例需要排序不同的字段时,例如,一个用例需要通过“name”排序,还有个想要根据“no”排序,或者有的用例需要通过“name和no”来排序。

Comparable:

应该在定义类时知道排序的顺序时使用,并且不会有其他任何需要使用Collection /数组来根据其他字段排序的情况。

注意:我没有介绍Set / List的细节。我假设读者已经了解了这些内容。此外,没有提供使用Set / array进行排序的详细示例,因为实现与ArrayList非常相似,而ArrayList我已经详细给出了示例。

最后,感谢阅读。

相关推荐

为何越来越多的编程语言使用JSON(为什么编程)

JSON是JavascriptObjectNotation的缩写,意思是Javascript对象表示法,是一种易于人类阅读和对编程友好的文本数据传递方法,是JavaScript语言规范定义的一个子...

何时在数据库中使用 JSON(数据库用json格式存储)

在本文中,您将了解何时应考虑将JSON数据类型添加到表中以及何时应避免使用它们。每天?分享?最新?软件?开发?,Devops,敏捷?,测试?以及?项目?管理?最新?,最热门?的?文章?,每天?花?...

MySQL 从零开始:05 数据类型(mysql数据类型有哪些,并举例)

前面的讲解中已经接触到了表的创建,表的创建是对字段的声明,比如:上述语句声明了字段的名称、类型、所占空间、默认值和是否可以为空等信息。其中的int、varchar、char和decimal都...

JSON对象花样进阶(json格式对象)

一、引言在现代Web开发中,JSON(JavaScriptObjectNotation)已经成为数据交换的标准格式。无论是从前端向后端发送数据,还是从后端接收数据,JSON都是不可或缺的一部分。...

深入理解 JSON 和 Form-data(json和formdata提交区别)

在讨论现代网络开发与API设计的语境下,理解客户端和服务器间如何有效且可靠地交换数据变得尤为关键。这里,特别值得关注的是两种主流数据格式:...

JSON 语法(json 语法 priority)

JSON语法是JavaScript语法的子集。JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔花括号保存对象方括号保存数组JS...

JSON语法详解(json的语法规则)

JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔大括号保存对象中括号保存数组注意:json的key是字符串,且必须是双引号,不能是单引号...

MySQL JSON数据类型操作(mysql的json)

概述mysql自5.7.8版本开始,就支持了json结构的数据存储和查询,这表明了mysql也在不断的学习和增加nosql数据库的有点。但mysql毕竟是关系型数据库,在处理json这种非结构化的数据...

JSON的数据模式(json数据格式示例)

像XML模式一样,JSON数据格式也有Schema,这是一个基于JSON格式的规范。JSON模式也以JSON格式编写。它用于验证JSON数据。JSON模式示例以下代码显示了基本的JSON模式。{"...

前端学习——JSON格式详解(后端json格式)

JSON(JavaScriptObjectNotation)是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScriptProgrammingLa...

什么是 JSON:详解 JSON 及其优势(什么叫json)

现在程序员还有谁不知道JSON吗?无论对于前端还是后端,JSON都是一种常见的数据格式。那么JSON到底是什么呢?JSON的定义...

PostgreSQL JSON 类型:处理结构化数据

PostgreSQL提供JSON类型,以存储结构化数据。JSON是一种开放的数据格式,可用于存储各种类型的值。什么是JSON类型?JSON类型表示JSON(JavaScriptO...

JavaScript:JSON、三种包装类(javascript 包)

JOSN:我们希望可以将一个对象在不同的语言中进行传递,以达到通信的目的,最佳方式就是将一个对象转换为字符串的形式JSON(JavaScriptObjectNotation)-JS的对象表示法...

Python数据分析 只要1分钟 教你玩转JSON 全程干货

Json简介:Json,全名JavaScriptObjectNotation,JSON(JavaScriptObjectNotation(记号、标记))是一种轻量级的数据交换格式。它基于J...

比较一下JSON与XML两种数据格式?(json和xml哪个好)

JSON(JavaScriptObjectNotation)和XML(eXtensibleMarkupLanguage)是在日常开发中比较常用的两种数据格式,它们主要的作用就是用来进行数据的传...

取消回复欢迎 发表评论:

请填写验证码