java 使用比较器对数组进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13201573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 11:51:10  来源:igfitidea点击:

Sorting an array using Comparator

javacomparator

提问by user1795189

I have the following code. When I try to compile it, it gives me the following error:

我有以下代码。当我尝试编译它时,它给了我以下错误:

The method sort(List<T>, Comparator<? super T>) in the type Collections is not 
applicable for the arguments (Software[], new Comparator(){}) 
The type new Comparator(){} must implement the inherited abstract method
Comparator.compare(Object, Object)

Code

代码

import java.text.DecimalFormat; // For proper currency  
import java.util.Comparator;
import java.util.Collections;


public class Software

{
// Declare variables

String SoftwareTitle; // SoftwareTitle
int SoftwareStock;    // Software totals
double SoftwarePrice; // Software Price
int SoftwareNum;      // Software Product ID
double CalculateInventory;  // To add inventory
double SoftwareValue;       // Software Total value
double value;               // Complete inventory total

Software( String softtitle, int softstock, double softprice, int softitemnum )

{
    // Create object constructor

    SoftwareTitle = softtitle;
    SoftwareStock = softstock;
    SoftwarePrice = softprice;
    SoftwareNum = softitemnum;

    } 

    // Set Software Title

    public void setSoftwareTitle( String softtitle )
    {
        SoftwareTitle = softtitle;
    } 


    // Return Software Title

    public String getSoftwareTitle()
    {
        return SoftwareTitle;
    } 

    // Set software inventory
    public void setSoftwareStock( int softstock)
    {
        SoftwareStock = softstock;
    } 

    // Return software inventory
    public int getSoftwareStock()
    {
        return SoftwareStock;
    }

    // Set software price

    public void setSoftwarePrice( double softprice )
    {
        SoftwarePrice = softprice;
    }

    // Return software price
    public double getSoftwarePrice()
    {
        return SoftwarePrice;

    }

    // Set item number

    public void setSoftwareNum( int softitemnum )
    {
        SoftwareNum = softitemnum;
          }         //

    //return software item number

    public int getSoftwareNum()
    {
        return SoftwareNum;
    } //


    // calculate inventory value

    public double Softwarevalue()
    {
        return SoftwarePrice * SoftwareStock;

    } 

    public void setCalculateInventory (double value){
        this.CalculateInventory = value;
    }



    public double getCalculateInventory(){
        double value = 0;
        for(int i = 0; i < 3; i++){
            value = Softwarevalue();
        }
        return value;
    }


 }//end method value

 //

import java.text.DecimalFormat; // For proper currency  
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;


 public class Inventory {

public static void main( String args[] )

{

    // Start array of software titles

    Software[] aSoftware = new Software[4];

    aSoftware[0]= new Software("Command and Conquer ", 6, 29.99, 10122); 
        aSoftware[1]= new Software("Alice in Wonderland", 1, 10.99,10233);
        aSoftware[2]= new Software("Doom", 1, 10.99, 10344);
    aSoftware[3]= new Software("Walking Dead", 6, 9.99, 10455);

//Set currency format
    DecimalFormat money = new DecimalFormat("
Arrays.sort(aSoftware, new Comparator<Software>() {
    public int compare(Software s1, Software s2) {
        return s1.getSoftwareTitle().compareTo(s2.getSoftwareTitle());
    }
});
.00"); // Sort in order of Software Name Collections.sort(aSoftware, new Comparator() { public int compare(Software s1, Software s2) { return s1.getSoftwareTitle().compareTo(s2.getSoftwareTitle()); } }); // Display software title, number of units, cost, item number and total inventory for (int i = 0; i < aSoftware.length; i++){ System.out.println("Software Title is "+ aSoftware[i].getSoftwareTitle() ); System.out.println("The number of units in stock is "+ aSoftware[i].getSoftwareStock() ); System.out.println("The price of the Software Title is "+ (money.format(aSoftware[i].getSoftwarePrice() ))); System.out.println( "The item number is "+ aSoftware[i].getSoftwareNum()); System.out.println( "The value of the Software Inventory is "+ (money.format(aSoftware[i].Softwarevalue() ))); System.out.println(); } //output total inventory value double total = 0.0; for (int i = 0; i < 3; i++){ total += aSoftware[i].getCalculateInventory(); } System.out.printf("Total Value of Software Inventory is: \t$%.2f\n", total); //end output total inventory value } } // //end

How do I get the software titles (an array) to display in alphabetical order using the Comparator?

如何使用比较器按字母顺序显示软件标题(数组)?

回答by Jon Skeet

You've got two problems:

你有两个问题:

1) You're using Collections.sort(which takes a List<E>), but trying to sort an array. Use Arrays.sortinstead.

1) 您正在使用Collections.sort(需要一个List<E>),但试图对数组进行排序。使用Arrays.sort来代替。

2) You need to specify that you're implementing Comparator<Software>, not just the raw Comparatortype.

2)您需要指定您正在实现Comparator<Software>,而不仅仅是原始Comparator类型。

So basically, this works:

所以基本上,这有效:

Arrays.sort(aSoftware);

回答by ruakh

Firstly: to sort an array, such as Software[], you need to use java.util.Arrays.sortrather than java.util.Collections.sort.

首先:要对数组进行排序,例如Software[],您需要使用java.util.Arrays.sort而不是java.util.Collections.sort

Secondly: since your Comparatoris specifically for Softwareinstances, you should write new Comparator<Software>()rather than merely new Comparator(). (The latter is actually bad code even when it does work.)

其次:由于您Comparator是专门针对Software实例的,您应该编写new Comparator<Software>()而不仅仅是new Comparator(). (后者实际上是糟糕的代码,即使它确实有效。)

回答by kosa

You can't sort on array when using Collections.sort. Collections.sortaccepts only List. user Arrays.sortrather than Collection.sort.

使用Collections.sort. Collections.sort只接受列表。用户Arrays.sort而不是Collection.sort.

回答by user3468976

Because you are trying to use array of object use below:

因为您正在尝试使用下面的对象数组:

@Override
public int compareTo(Software o) {
    return this.getSoftwareTitle().compareTo(o.getSoftwareTitle());
}

and your software class should implements implements Comparable and override its compareTo method:

并且您的软件类应该实现实现 Comparable 并覆盖其 compareTo 方法:

public class Software implements Comparable<Software>{
// Declare variables

String SoftwareTitle; // SoftwareTitle
int SoftwareStock; // Software totals
double SoftwarePrice; // Software Price
int SoftwareNum; // Software Product ID
double CalculateInventory; // To add inventory
double SoftwareValue; // Software Total value
double value; // Complete inventory total

Software(){

}

Software(String softtitle, int softstock, double softprice, int softitemnum)

{
    // Create object constructor

    SoftwareTitle = softtitle;
    SoftwareStock = softstock;
    SoftwarePrice = softprice;
    SoftwareNum = softitemnum;

}

// Set Software Title

public void setSoftwareTitle(String softtitle) {
    SoftwareTitle = softtitle;
}

// Return Software Title

public String getSoftwareTitle() {
    return SoftwareTitle;
}

// Set software inventory
public void setSoftwareStock(int softstock) {
    SoftwareStock = softstock;
}

// Return software inventory
public int getSoftwareStock() {
    return SoftwareStock;
}

// Set software price

public void setSoftwarePrice(double softprice) {
    SoftwarePrice = softprice;
}

// Return software price
public double getSoftwarePrice() {
    return SoftwarePrice;

}

// Set item number

public void setSoftwareNum(int softitemnum) {
    SoftwareNum = softitemnum;
} //

// return software item number

public int getSoftwareNum() {
    return SoftwareNum;
} //

// calculate inventory value

public double Softwarevalue() {
    return SoftwarePrice * SoftwareStock;

}

public void setCalculateInventory(double value) {
    this.CalculateInventory = value;
}

public double getCalculateInventory() {
    double value = 0;
    for (int i = 0; i < 3; i++) {
        value = Softwarevalue();
    }
    return value;
}

@Override
public int compareTo(Software o) {
    return this.getSoftwareTitle().compareTo(o.getSoftwareTitle());
}





}// end method value

I have made correction to your class as below:

我对你的班级做了如下更正:

public class Inventory {

public static void main(String args[])

{

    // Start array of software titles

    Software[] aSoftware = new Software[4];

    aSoftware[0] = new Software("Command and Conquer ", 6, 29.99, 10122);
    aSoftware[1] = new Software("Alice in Wonderland", 1, 10.99, 10233);
    aSoftware[2] = new Software("Doom", 1, 10.99, 10344);
    aSoftware[3] = new Software("Walking Dead", 6, 9.99, 10455);

    // Set currency format
    DecimalFormat money = new DecimalFormat("
Software Title is Alice in Wonderland
The number of units in stock is 1
The price of the Software Title is .99
The item number is 10233
The value of the Software Inventory is .99

Software Title is Command and Conquer 
The number of units in stock is 6
The price of the Software Title is .99
The item number is 10122
The value of the Software Inventory is 9.94

Software Title is Doom
The number of units in stock is 1
The price of the Software Title is .99
The item number is 10344
The value of the Software Inventory is .99

Software Title is Walking Dead
The number of units in stock is 6
The price of the Software Title is .99
The item number is 10455
The value of the Software Inventory is .94

Total Value of Software Inventory is:   1.92
.00"); Arrays.sort(aSoftware); // Display software title, number of units, cost, item number and total // inventory for (int i = 0; i < aSoftware.length; i++) { System.out.println("Software Title is " + aSoftware[i].getSoftwareTitle()); System.out.println("The number of units in stock is " + aSoftware[i].getSoftwareStock()); System.out.println("The price of the Software Title is " + (money.format(aSoftware[i].getSoftwarePrice()))); System.out.println("The item number is " + aSoftware[i].getSoftwareNum()); System.out.println("The value of the Software Inventory is " + (money.format(aSoftware[i].Softwarevalue()))); System.out.println(); } // output total inventory value double total = 0.0; for (int i = 0; i < 3; i++) { total += aSoftware[i].getCalculateInventory(); } System.out.printf("Total Value of Software Inventory is: \t$%.2f\n", total); // end output total inventory value } }

Your Inventory class:

您的库存类:

##代码##

Below is final output in sorted order:

以下是按排序顺序的最终输出:

##代码##

回答by Mitch Connor

You should make your "Software" class implement comparable and then overwrite the compare method to return a compare on the titles like you did outside your code. This will be a replacement for the comparator. Then all you need to to is call Arrays.sort.

您应该使您的“软件”类实现可比性,然后覆盖 compare 方法以返回对标题的比较,就像您在代码之外所做的那样。这将是比较器的替代品。然后你需要做的就是调用 Arrays.sort。