简体   繁体   English

如何在 Java 中按字母顺序对数组中的自定义对象进行排序?

[英]How do I sort custom objects alphabetically in an array in Java?

How would I sort my inventory array alphabetically?如何按字母顺序对inventory数组进行排序?

This is for a project that I am working on.这是我正在做的一个项目。 I tried to use Arrays.sort(inventory);我尝试使用Arrays.sort(inventory); but it did not work.但它没有用。

Could someone please tell me what I am doing wrong?有人可以告诉我我做错了什么吗?

Book class:书类:

//Filename: BookStore.java
//Description: Purpose is to display what books are in stock and ISBN, title, author name, year, publishers name, and price.
//Author Name: David Finocchi
//Date: 01/19/2014
import java.util.Arrays;
import java.text.DecimalFormat;

class Book {
    protected long isbn;
    protected String title;
    protected String autName;
    protected int year;
    protected String pubName;
    protected double price;
    protected int quantity;


    // Constructor
    public Book(long isbn, String title, String autName, int year, String pubName, double price) {
        setIsbn(isbn);
        setTitle(title);
        setAut(autName);
        setYear(year);
        setPub(pubName);
        setPrice(price);
    }

    // methods for class variables
    public long getIsbn() {
        return isbn;
    }

    public void setIsbn(long isbn) {
        this.isbn = isbn;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAut() {
        return autName;
    }

    public void setAut(String autName) {
        this.autName = autName;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public String getPub() {
        return pubName;
    }

    public void setPub(String pubName) {
        this.pubName = pubName;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    public double calTotal() {
        return price;
    }

    //toString for the book array
    public String toString() {
        return "ISBM: " + isbn + "\n" + "Title: " + title + "\n" + "Author's Name: " + autName + "\n" + "Year Published: " + year + "\n" + "Publisher's Name: " + pubName + "\n" + "Price: $" + price + "\n\n";
    }

}// end class Book

EBook class:电子书类:

class EBook extends Book {

    private String website;

    //constructor and super
    public EBook(long isbn, String title, String autName, int year,
                 String pubName, double price, String website) {
        super(isbn, title, autName, year, pubName, price);
        setWebsite(website);
    }

    // get and set
    public String getWebsite() {
        return website;
    }


    public void setWebsite(String website) {
        this.website = website;
    }

    public double discount() {
        return price * 0.10;
    }

    DecimalFormat money = new DecimalFormat("$0.00");

    //toString for the Book array
    public String toString() {
        return "ISBM: " + isbn + "\n" + "Title: " + title + "\n" + "Author's Name: " + autName + "\n" + "Year Published: " + year + "\n" + "Publisher's Name: " + pubName + "\n" + "Price: " + money.format(price) + "\n" + "Website: " + website + "\n" + "Discount: " + money.format(discount()) + "\n\n";
    }

}//end class EBook

BookStore class (with main method): BookStore 类(使用 main 方法):

public class BookStore {
    //main method
    public static void main(String[] args) {
        // book array
        Book[] inventory = new Book[5];

        EBook a = new EBook(75260012L, "David goes to School", "David Shannon", 2010, "Shannon Rock", 11.98, "http://www.tinyurl.qqwert67o9");
        Book b = new Book(7423540089L, "No David!", "David Shannon", 2009, "Shannon Rock", 12.99);
        Book c = new Book(743200616L, "Simple Abundance", "Sarah Breathnach", 2009, "Scribner", 14.99);
        EBook d = new EBook(78137521819L, "The very hungry caterpillar", "Eric Carle", 2005, "Philomel Books", 13.99, "http://www.tinyurl.fguopt8u90");
        Book e = new Book(9781416987116L, "We're going on a bear hunt", "Michael Rosen", 2009, "McElderry", 15.99);

        inventory[0] = a;
        inventory[1] = b;
        inventory[2] = c;
        inventory[3] = d;
        inventory[4] = e;

        double total = 0.0;

        //print text to user
        System.out.println("Bookstore Items:" + "\n");
        //print array
        for (int i = 0; i < inventory.length; i++) {
            System.out.println(inventory[i]);
            total += inventory[i].getPrice();
        }
        //print total
        DecimalFormat money = new DecimalFormat("$0.00");
        System.out.printf("Total Inventory Value: " + money.format(total));
    }

}// end class BookStore

Arrays.sort() uses the natural ordering of the objects, so that would imply that you need them to implement Comparable , or you're going to get unreliable sorting behavior. Arrays.sort()使用对象的自然顺序,因此这意味着您需要它们来实现Comparable ,否则您将获得不可靠的排序行为。

Simply put, if you want to sort each book by its title, then have it implement Comparable :简单地说,如果你想按书名对每本书进行排序,那么让它实现Comparable

public class Book implements Comparable<Book> {
    public int compareTo(Book otherBook) {
        return title.compareTo(otherBook.getTitle());
    }
}

You'd also want to do the same for the subclass EBook as well.您还希望EBookEBook执行相同的操作。

You can`t just sort string attribute of a class by directly putting that class to array.sort.您不能通过直接将类放入 array.sort 来对类的字符串属性进行排序。 If you use the array list rather than array, then you could use the Collection.sort() to sort the list using field inside the book object.如果您使用数组列表而不是数组,那么您可以使用 Collection.sort() 使用 book 对象内的字段对列表进行排序。

public static void main(String[] args) {公共静态无效主(字符串 [] args){

// book array

ArrayList<Book> inventory = new ArrayList<Book>();

inventory.add (new Book(9781416987116L, "We're going on a bear hunt", "Michael Rosen", 2009, "McElderry", 15.99));
inventory.add (new Book(743200616L, "Simple Abundance", "Sarah Breathnach", 2009, "Scribner", 14.99));
inventory.add(new EBook(75260012L, "David goes to School", "David Shannon", 2010, "Shannon Rock", 11.98, "http://www.tinyurl.qqwert67o9"));
inventory.add (new Book(7423540089L, "No David!", "David Shannon", 2009, "Shannon Rock", 12.99));
inventory.add (new EBook(78137521819L, "The very hungry caterpillar", "Eric Carle", 2005, "Philomel Books", 13.99, "http://www.tinyurl.fguopt8u90"));

Collections.sort(inventory, new Comparator<Book>() {
    public int compare(Book result1, Book result2) {
        return result1.getTitle().compareTo(result2.getTitle());
    }
});

for (int i =0;i<inventory.size();i++){
    System.out.println(inventory.get(i).getTitle());
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在java中按字母顺序对字符串数组进行排序? - How do I sort an array of strings alphabetically in java? Java-按字母和数字顺序对带有对象的数组列表进行排序 - Java - Sort Array List with Objects Alphabetically and Numerically 如何在 Java 中按字母顺序对枚举成员进行排序? - How do I sort enum members alphabetically in Java? 如何在java中按字母顺序对二维数组进行排序 - How to alphabetically sort two dimensional array in java 如何在 Java 中按字母顺序组织对象数组 - How to organise alphabetically an array of objects in Java 如何按字母顺序对JList中的项目排序? - How do I sort items in a JList alphabetically? 如何按字母顺序对文本文件进行排序? - How do I sort a text file alphabetically? 如何按字母顺序对由自定义类对象组成的树集按其字段之一排序 - How to sort alphabetically treeset consisting of custom class objects by one of their fields 如何按字母顺序对 listView 的文件进行排序并集成列表适配器?我正在使用自定义适配器 - How do i sort alphabetically the files of my listView and integrate a list adapter?I'm using a custom adapter 按字母顺序对字符串数组进行排序。 如何按每行中间的数字对同一数组进行排序 - Sorted an array of strings alphabetically. How do I sort the same array by a number in the middle of each line
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM