开发者

Sorting Array in natural order

开发者 https://www.devze.com 2023-02-03 20:42 出处:网络
OK, using your implement Comparator.It returns errors complaing about the string value being incompa开发者_运维问答tible with the return int.

OK, using your implement Comparator. It returns errors complaing about the string value being incompa开发者_运维问答tible with the return int.

class cdinventoryItem implements Comparable<cdinventoryItem> {

        private String Ptitle;
        private int PitemNumber;
        private int PnumberofUnits;
        private double PunitPrice;
        private double Evalue;


        public cdinventoryItem(String title, int itemNumber, int numberofUnits, double unitPrice ){

                Ptitle = title;
                PitemNumber = itemNumber;
                PnumberofUnits = numberofUnits;
                PunitPrice = unitPrice;

        }
 public int compareTo(cdinventoryItem otherItem) {
    return this.Ptitle.compareTo(otherItem.getTitle());
  }

  public int getTitle() {
    return Ptitle;
  }



        public double stockValue () {
            return PnumberofUnits * PunitPrice;
        }


        public double getEntireStockValue () {
            Evalue = Evalue + this.stockValue();
            return Evalue;
        }


        @Override public String toString(){


            NumberFormat dformat = new DecimalFormat("#0.00");


            StringBuilder ouput  = new StringBuilder();
            String New_Line = System.getProperty("line.separator");

                ouput.append ("The product number of my CD is: " + PitemNumber + New_Line);
                ouput.append ("The title of the CD is: " + Ptitle + New_Line);
                ouput.append ("I have " + PnumberofUnits + " units in stock." + New_Line);
                ouput.append ("The total value of my inventory on this product is: " + dformat.format (stockValue()) + New_Line);
                return ouput.toString();
            }

}



public class cdinventoryprogram {

    public static void main(String[] args) {

    NumberFormat dformat = new DecimalFormat("#0.00");
    double Tvalue= 0.0;

    int DEFAULT_LENGTH = 3;

        System.out.println ("Welcome to my CD inventory program!!");
        System.out.println ("");


            cdinventoryItem  initem[] = new cdinventoryItem [DEFAULT_LENGTH];

            initem [0] = new cdinventoryItem ("The Illusionist", 1, 5, 15.99);
            initem [1] = new cdinventoryItem ("Matrix", 2, 3, 14.99);
            initem [2] = new cdinventoryItem ("Old School", 3, 6, 12.99);


            Arrays.sort(initem,
            new Comparator<cdinventoryItem>() {
            public int compare(cdinventoryItem item1, cdinventoryItem item2) {
            return item1.getTitle().compareTo(item2.getTitle());
    }});

                for ( cdinventoryItem currentcdinventoryItem : initem ){
                System.out.println( currentcdinventoryItem );
                Tvalue = Tvalue + currentcdinventoryItem.getEntireStockValue();
                }

                System.out.println ("The total value of my entire inventory is:");
                System.out.println ( "$" + dformat.format (Tvalue));
                System.out.println();
    }}


That happens because you are trying to sort an array of cdinventoryItem objects, but cdinventoryItem does not implement Comparable. Thus, Arrays.sort does not have a clue about how to sort your array. You need to implement Comparable in order to determine the natural order of your objects.

For example, if you want to order it by title:

public class cdinventoryItem implements Comparable<cdinventoryItem> {
  // your code

  public int compareTo(cdinventoryItem otherItem) {
    return this.Ptitle.compareTo(otherItem.getTitle());
  }

  public String getTitle() {
    return Ptitle;
  }
}

Alternatively, you could use Arrays.sort(T[], java.util.Comparator), and define a custom sort method to be used:

cdinventoryItem initem[] = new cdinventoryItem[DEFAULT_LENGTH];
// fill array
Arrays.sort(initem, 
  new Comparator<cdInventoryItem>() {
    public int compare(cdInventoryItem item1, cdInventoryItem item2) {
        return item1.getTitle().compareTo(item2.getTitle());
    }
  }
);

PS: Please try to follow Oracle's naming conventions. For instance, Java class names should be nouns, in mixed case with the first letter of each internal word capitalized. So, instead of cdInventoryItem, you should have CdInventoryItem.


You need to either make your cdinventoryItem class implement the Comparable interface, or write an implementation of Comparator. In either case, you implement the logic for deciding which element comes first and return either -1, 1, or 0 to represent before, after or the same.

e.g.

class cdinventoryItem() implements Comparable<cdinventoryItem> {
    ...
    public int compareTo(cdinventoryItem other) {
        return this.Ptitle.compareTo(other.Ptitle);
    }
}

Since String implements Comparable you can just delegate to that.


I think the problem is that the objects you're trying to compare don't have an ordering defined on them because they don't implement the Comparable interface. Consequently, when the provided sort routines try to figure out what order the elements should go in, it finds it has no way to do so and gives up.

To fix this,try implementing the Comparable interface with compareTo. Alternatively, define a custom Comparator class and pass it as a parameter to Arrays.sort.


It means exactly what it says: it can't sort a list of cdinventoryItem, because they aren't Comparable: i.e., it has no idea how to compare them. How do you expect to put things in order if you can't look at two of them and say which should go in front of the other?

How do you want them to be sorted, and why? (After all, the stock value does not change if you re-order the stock...)


You have to tell sort how to compare objects other than primitive types or Strings (and some others that implement the Comparable interface). Java has no idea how to sort a cdinventoryItem.

You can either: 1) Make cdinventoryItem implement the Comparable interface and implement the method:

public int compareTo(Object o) Returns -1, 0, 1 if the item is less then, equal to, or greater then o, respectively. (http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Comparable.html)

2) Pass a Comparator object to the sort method that takes two objects and returns -1, 0, 1 if the first object compares less then, equal to or greater then the second object respectively.

http://download.oracle.com/javase/1.4.2/docs/api/java/util/Comparator.html


You can try the Bean Comparator.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号