如何在Java中对对象数组进行排序? [英] How to sort an array of objects in Java?

查看:30
本文介绍了如何在Java中对对象数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数组不包含任何字符串.但它包含对象引用.每个对象引用都通过 toString 方法返回名称、ID、作者和出版商.

My array does not contain any string. But its contains object references. Every object reference returns name, id, author and publisher by toString method.

public String toString() {
        return (name + "
" + id + "
" + author + "
" + publisher + "
");
}

现在我需要按名称对该对象数组进行排序.我知道如何排序,但我不知道如何从对象中提取名称并对其进行排序.

Now I need to sort that array of objects by the name. I know how to sort, but I do not know how to extract the name from the objects and sort them.

推荐答案

您有两种方法可以做到这一点,都使用 数组 实用程序类

You have two ways to do that, both use the Arrays utility class

  1. 实现一个 Comparator 并将您的数组与比较器一起传递到 sort 方法 将其作为第二个参数.
  2. 在您的对象来自的类中实现Comparable 接口并将您的数组传递给 排序方法 只接受一个参数.
  1. Implement a Comparator and pass your array along with the comparator to the sort method which take it as second parameter.
  2. Implement the Comparable interface in the class your objects are from and pass your array to the sort method which takes only one parameter.

示例

class Book implements Comparable<Book> {
    public String name, id, author, publisher;
    public Book(String name, String id, String author, String publisher) {
        this.name = name;
        this.id = id;
        this.author = author;
        this.publisher = publisher;
    }
    public String toString() {
        return ("(" + name + ", " + id + ", " + author + ", " + publisher + ")");
    }
    @Override
    public int compareTo(Book o) {
        // usually toString should not be used,
        // instead one of the attributes or more in a comparator chain
        return toString().compareTo(o.toString());
    }
}

@Test
public void sortBooks() {
    Book[] books = {
            new Book("foo", "1", "author1", "pub1"),
            new Book("bar", "2", "author2", "pub2")
    };

    // 1. sort using Comparable
    Arrays.sort(books);
    System.out.println(Arrays.asList(books));

    // 2. sort using comparator: sort by id
    Arrays.sort(books, new Comparator<Book>() {
        @Override
        public int compare(Book o1, Book o2) {
            return o1.id.compareTo(o2.id);
        }
    });
    System.out.println(Arrays.asList(books));
}

输出

[(bar, 2, author2, pub2), (foo, 1, author1, pub1)]
[(foo, 1, author1, pub1), (bar, 2, author2, pub2)]

这篇关于如何在Java中对对象数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆