2012-01-02 23 views
27
import java.util.HashMap; 
import java.io.*; 
import java.util.*; 
public class Fegan implements Comparable{ 
HashMap<String, Integer> cart = new HashMap<String, Integer>(); 
List list = new ArrayList<FoodItems>(); 
int x =0; 
public void addToCart(FoodItems f) 
{ 
    cart.put(f.name, f.valueOfFood); 
} 
public String display(FoodItems f) 
{ 
    return(f.name + " costs " + f.valueOfFood); 
} 
public void addToList(FoodItems f) 
{ 
    //FoodItems temp = (FoodItems) f; 
    list.add(f); 
} 
public int compareTo(Object o) 
{ 
    //FoodItems temp = (FoodItems) o; 
    if(this.x == ((FoodItems)o).valueOfFood) 
     return 0; 
    else if (this.x <((FoodItems)o).valueOfFood) 
     return 1; 
    else 
     return -1; 
} 
public void sortMap(List list) 
{ 
    for(int i =0; i< list.size(); i++) 
    { 
     FoodItems temp = (FoodItems) list.get(i); 
     cart.put(temp.name, temp.valueOfItem); 

    } 
} 
} 

import java.util.Collections; 
import java.util.HashMap; 
import java.util.Iterator; 
import java.io.*; 
import java.util.*; 
public class Test { 
public static void main(String [] args) 
{ 
    HashMap<String, Integer> cart = new HashMap<String, Integer>(); 
    FoodItems firts = new FoodItems("Chocolate" , 50); 
    FoodItems second = new FoodItems("Juice", 79); 
    FoodItems third = new FoodItems("Apple", 200); 
    FoodItems forth = new FoodItems("Orange", 300); 
    FoodItems fifth = new FoodItems("Milk" , 400); 
    ArrayList items = new ArrayList(); 
    items.add(firts); 
    items.add(second); 
    items.add(third); 
    items.add(forth); 
    items.add(fifth); 
    Collections.sort(items); 
    Iterator itr = items.iterator(); 
    Fegan myFegan = new Fegan(); 
    myFegan.sortMap(items); 

    while(itr.hasNext()){ 
     Object element = itr.next(); 
     System.out.println(element + "\n"); 
    } 
} 
} 

Perché è scritturanon può essere gettato a java.lang.Comparable

Exception in thread "main" java.lang.ClassCastException: FoodItems cannot be cast to java.lang.Comparable 
at java.util.ComparableTimSort.countRunAndMakeAscending(Unknown Source) 
at java.util.ComparableTimSort.sort(Unknown Source) 
at java.util.ComparableTimSort.sort(Unknown Source) 
at java.util.Arrays.sort(Unknown Source) 
at java.util.Collections.sort(Unknown Source) 
at Test.main(Test.java:21) 

Grazie in anticipo!

+0

Pubblica la fonte per FoodItems – AlanFoster

risposta

16
  • l'oggetto che implementa Comparable è Fegan.

Il metodo compareTo si sta overidding in esso dovrebbe avere un oggetto Fegan come parametro, mentre si sta lanciando in una FoodItems. L'implementazione compareTo dovrebbe descrivere come confrontare un Fegan con un altro Fegan.

  • fare effettivamente il vostro ordinamento, si potrebbe desiderare di fare il vostro FoodItems implementare Comparable lontato e copia incolla il tuo attuale compareTo logica in esso.
Problemi correlati