web123456

Java Jobs - Collection Sort (TreeMap)

  • package Five;
  • import ;
  • import ;
  • import ;
  • /**
  • * There are 10 USB drives, with two important attributes: price and capacity.
  • * Write an application, use the TreeMap<> class to sort the details of 10 USB flash drives by price and capacity respectively.
  • * @author Vivinia
  • *
  • * December 25, 2017
  • */
  • //Package class of value, container and price
  • public class Disk {
  • double amount; //capacity
  • double price; //price
  • Disk(double amount,double price){
  • this.amount=amount;
  • this.price=price;
  • }
  • }
  • //key, and rewrite the compareTo method
  • class Key implements Comparable{
  • double key=0;
  • Key(double key){
  • this.key=key;
  • }
  • @Override
  • public int compareTo(Object o) {
  • Key k=(Key)o;
  • if(this.key==)
  • return 0; //Equal return 0
  • else
  • return (int)(this.); //The first big returns a positive number, and the next big returns a negative number
  • }
  • }
  • //Test class
  • class Test{
  • static int i;
  • static Disk disk[];
  • static Key key[];
  • static TreeMap<Key,Disk> treemap;
  • public static void main(String[] args) {
  • treemap=new TreeMap<Key,Disk>();
  • disk=new Disk[6];
  • key=new Key[6];
  • double amount[]= {1,2,4,8,16,32}; //Capacity array
  • double price[]= {25,18,32,80,64,120}; //Price array
  • for(i=0;i<;i++)
  • disk[i]=new Disk(amount[i],price[i]); //Package capacity and price into Disk instance
  • ("Sorted by capacity:");
  • save(amount); //Pass capacity data as key
  • (); //Clear the previous data
  • ("Sorted by price:");
  • save(price); //Pass price data as key
  • }
  • //Storage method
  • public static void save(double comKey[]) { //The parameter is the keyword you want to sort, it can be capacity or price
  • for(i=0;i<;i++) {
  • key[i]=new Key(comKey[i]);
  • (key[i],disk[i]);
  • }
  • Collection<Disk> c=(); //Get the value set in the treemap collection
  • Iterator<Disk> it=();
  • while(()) {
  • Disk d=();
  • ("capacity"++"GB,"++"Yuan");
  • }
  • }
  • }