问题1:我想将以下“Class Dog”的“特定”排序值添加到“Ser”类中使用的“Map”中。但我不知道如何实现这一点,
问题 2:如果成功填充,如何访问地图的填充值
以下是我绝望的尝试。
class Dog implements Comparator<Dog>, Comparable<Dog>{
private double Price;
private String Operator;
Dog(){
}
Dog( double p, String o){
Price= p;
Operator=o;
}
public double getPrice(){
return Price;
}
public String getOperator(){
return Operator;
}
// Overriding the compareTo method
public int compareTo(Dog d){
double data= Price - d.Price;
if ( data > 0.00001)return 1;
if (data < 0.00001) return -1;
return 0;
}
// Overriding the compare method to sort the age
public int compare(Dog d, Dog d1){
double data= d.Price - d1.Price;
if ( data > 0.00001)return 1;
if (data < 0.00001) return -1;
return 0;
}
}
public class Ser {
/**
* @param args
*/
public static void main(String[] args) {
// Takes a list o Dog objects
ArrayList <Dog> list1 = new ArrayList<Dog>();
Map <Integer, ArrayList<Dog> > map= new HashMap <Integer, ArrayList<Dog> > ();
list1.add(new Dog(0.99 , "A"));
list1.add(new Dog(0.91 , "C"));
list1.add(new Dog(0.92 , "A"));
list1.add(new Dog(0.97 , "B"));
list1.add(new Dog( 0.93 , "C"));
list1.add(new Dog(0.97 , "B"));
list1.add(new Dog(0.92, "A"));
list1.add(new Dog(0.97, "C"));
list1.add(new Dog(0.92, "A"));
// Sorts the array list using comparator
Collections.sort(list1, new Dog());
for(Dog a: list1)//printing the sorted list of ages
System.out.println( a.getOperator()+" : "+ a.getPrice());
map.put(92, list1);
map.put(445, list1);
map.put(966, list1);
// Collections.sort(list1, new Dog());
for (ArrayList<Dog> key: map.values() )
System.out.println(key);
}
}
输出:C:0.91,A:0.92,A:0.92,A:0.92,C:0.93,C:0.97,B:0.97,B:0.97,A:0.99
地图值的输出:[Dog@a981ca, Dog@8814e9, Dog@1503a3, Dog@1a1c887, Dog@743399, Dog@e7b241, Dog@167d940, Dog@e83912, Dog@1fae3c6] [Dog@a981ca, Dog@8814e9 , Dog@1503a3, Dog@1a1c887, Dog@743399, Dog@e7b241, Dog@167d940, Dog@e83912, Dog@1fae3c6] [Dog@a981ca, Dog@8814e9, Dog@1503a3, Dog@1a1c887, Dog@743399,狗@e7b241、狗@167d940、狗@e83912、狗@1fae3c6]