【问题标题】:Sorting object on based on 4 attributes of a Class in java基于java中类的4个属性对对象进行排序
【发布时间】:2014-04-12 05:57:40
【问题描述】:

我是java新手 我有一个有 4 个属性的类,我需要根据它对我的对象进行排序。我可以在 Author , title 和 price 上实现三个级别的排序,任何人都可以帮助我将其扩展到出版商。

我的代码: 首先根据作者姓名对对象进行排序,如果作者姓名相同,则按标题排序,如果标题相同,则按价格排序。

现在我想如果价格相同,按出版商排序。谁能帮我解决这个问题?

代码如下:

//Book.java

public class Book implements Comparable<Book>{

   String title;
   String author;
   double price;
   String publisher;
    //getters and setters for 4 variables
public int compareTo(Book book){

     if(book == null){
       throw new NullPointerException("Book passed is null!"); 
    }

    if(this.getAuthor().equals(book.getAuthor())){  /*Most significant field*/

     if(this.getTitle().equals(book.getTitle()))   /*Next Most significant field*/ 
            return (int)(this.getPrice()-book.getPrice());
          else
           return this.getTitle().compareTo(book.getTitle());
     }
     else
          return this.getAuthor().compareTo(book.getAuthor());

  }
}

//BookComparison.java

import java.util.Arrays;

public class BookComparision{

    public static void main(String args[]){

        Book book1 = new Book();        
        book1.setAuthor("Author A");
        book1.setTitle("Title B");
        book1.setPrice(225.00);

        Book book2 = new Book();        
        book2.setAuthor("Author A");
        book2.setTitle("Title B");
        book2.setPrice(125.00);


        Book book3 = new Book();        
        book3.setAuthor("Author B");
        book3.setTitle("Title B");
        book3.setPrice(125.00);

        Book book4 = new Book();        
        book4.setAuthor("Author B");
        book4.setTitle("Title A");
        book4.setPrice(200.00);


        Book book5 = new Book();        
        book5.setAuthor("Author C");
        book5.setTitle("Title C");
        book5.setPrice(125.00);

        Book book6 = new Book();        
        book6.setAuthor("Author C");
        book6.setTitle("Title B");
        book6.setPrice(125.00);

        Book book7 = new Book();        
        book7.setAuthor("Author C");
        book7.setTitle("Title B");
        book7.setPrice(400.00);

       /* An array containing Books*/
        Book[] bookArray = new Book[7];
        bookArray[0]=book1;
        bookArray[1]=book2;
        bookArray[2]=book3;
        bookArray[3]=book4;
        bookArray[4]=book5;
        bookArray[5]=book6;
        bookArray[6]=book7;

        System.out.println("Sorted Books:");

        Arrays.sort(bookArray);

        for(int i=0;i<=6;i++){
        System.out.print("Author:"+bookArray[i].getAuthor()+"        ");
        System.out.print("Title:"+bookArray[i].getTitle()+"        ");
        System.out.println("Price:"+bookArray[i].getPrice());

        }        
   }
 }

提前致谢 玛纳斯

【问题讨论】:

  • 如果您能够实现对 4 个元素的排序,那么实现另一个条件的问题在哪里?旁注:请始终使用大括号,它使您的代码更具可读性且不易出错。
  • 嗨 Leos,到目前为止,我可以按 3 个属性对其进行排序,即作者、标题和价格。但我想将排序扩展到 Publisher。上面的代码仅对 3 个属性而不是第 4 个不基于发布者的属性进行排序
  • 好吧,我会尽量让它更具可读性。但是,您延长条件的问题在哪里?
  • 比较作者。如果不相等,你就完成了。然后比较标题。如果不相等,你就完成了。然后比较价格。如果不相等,你就完成了。然后比较出版商。比较使用的是 compareTo() 方法,而不是 equals() 方法。

标签: java sorting object


【解决方案1】:

您已经有了正确的想法:比较每个标准,直到有一个不相等。只需以更有条理的方式进行即可。

int dif;

dif = this.getAuthor().compareTo(book.getAuthor());
if(dif != 0)
    return dif;

dif = this.getTitle().compareTo(book.getTitle());
if(dif != 0)
    return dif;

if(this.getPrice() < book.getPrice())
    return -1;
if(this.getPrice() > book.getPrice())
    return 1;

return this.getPublisher().compareTo(book.getPublisher());

请注意,我没有使用减法来比较 double 的值。执行(int)(double - double) 会截断小数值,这可能不是一个好主意。如果您使用的是较新的 JDK,还有一些静态方法,例如 Double.compare

【讨论】:

    【解决方案2】:

    如果您使用String 字段来比较对象,您总是可以依靠Strings 本身的自然顺序。如果您有多个标准,则可以按时间顺序使用它们,如下所示:

    public int compareTo(Book b)
    {
        int compare = title.compareTo(b.getTitle());
    
        // the following lines only change the compare value if it is still 0
        compare = (compare != 0) ? compare : author.compareTo(b.getAuthor()); 
        compare = (compare != 0) ? compare : Double.compare(price, b.getPrice());
    
        return (compare != 0) ? compare : publisher.compareTo(b.getPubisher());
    }
    

    我也不会将 +- 之类的操作与双精度数一起使用,因为它们在转换为 int 时不够准确。想象一下价格为 19.90 和 19.95 的书籍的总和为 int 0,这将被视为相等(从订购的角度来看)。

    【讨论】:

    • 提示:Integer.compare(i1, i2).
    【解决方案3】:

    与您一直使用的相同方法保持一致,如果您想为 if same price --&gt; sort by publisher 添加第 4 层比较,我会这样做:

    public int compareTo(Book book){
    
         if(book == null){
           throw new NullPointerException("Book passed is null!"); 
         }
    
         if(this.getAuthor().equals(book.getAuthor())){  /*Most significant field*/
    
           if(this.getTitle().equals(book.getTitle()))   /*Next Most significant field*/ 
               if(this.getPublisher().equals(book.getPublisher())){ //assuming that you have a getPublisher() method
                   return (int)(this.getPublisher().compareTo(book.getPublisher()));
               }
               else {
                   return (int)(this.getPrice()-book.getPrice());
               }
           else
               return this.getTitle().compareTo(book.getTitle());
           }
         else
            return this.getAuthor().compareTo(book.getAuthor());
    
        }
    }
    

    【讨论】:

    • 感谢 Wold,此解决方案对您有帮助
    • @user3507026 没问题,很高兴能帮上忙。答案解决了你的问题吗?
    【解决方案4】:

    你可以试试这样的。

    public int compareTo(Book book) {
    
        int retval = author.compareTo(book.author);
        if(retval != 0) return retval;
    
        retval = title.compareTo(book.title);
        if(retval != 0) return retval;
    
        if(price!=book.price) return price>book.price ? 1 : -1;
    
        // if we reach here, all previous comparisons are equal. So just return whatever publisher compareTo returns.
        return publisher.compareTo(book.publisher);
    
    }
    

    【讨论】:

      【解决方案5】:

      这是 cmets 中讨论的代码。它更容易定位。

      public int compareTo(Book book) {
      
          if (book == null) {
              throw new NullPointerException("Book passed is null!");
          }
      
          if (!this.getAuthor().equals(book.getAuthor())) {
              return this.getAuthor().compareTo(book.getAuthor());
          }
      
          if (! this.getTitle().equals(book.getTitle())) {
              return this.getTitle().compareTo(book.getTitle());
          }
      
          if (this.getPrice() != book.getPrice()) {
              return (int) (this.getPrice() - book.getPrice());
          }
      
          return publisher.compareTo(book.getPublisher());
      }
      

      【讨论】:

        【解决方案6】:
          public int compareTo(Book book){
        
         if(book == null){
           throw new NullPointerException("Book passed is null!"); 
        }
        
        if(this.getAuthor().equals(book.getAuthor())){  /*Most significant field*/
        
         if(this.getTitle().equals(book.getTitle())){   /*Next Most significant field*/ 
           if(this.getPrice().equals(book.getPrice()){
              return (this.getPublisher().compareTo(book.getPublisher()); 
          }  
            else{
                  return (int)(this.getPrice()-book.getPrice());
                }         
           }
              else{
               return this.getTitle().compareTo(book.getTitle());
         }}
         else{
              return this.getAuthor().compareTo(book.getAuthor());
             }
             }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-07-19
          • 2015-12-13
          • 1970-01-01
          • 2013-03-13
          • 2017-09-19
          • 1970-01-01
          • 2018-04-21
          • 1970-01-01
          相关资源
          最近更新 更多