问题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
映射值的输出:
[狗@ a981ca,狗@ 8814e9,狗@ 1503a3,狗@ 1a1c887,狗@ 743399,狗@ e7b241,狗@ 167d940,狗@ e83912,狗@ 1fae3c6]
[狗@ a981ca,狗@ 8814e9,狗@ 1503a3,狗@ 1a1c887,狗@ 743399,狗@ e7b241,狗@ 167d940,狗@ e83912,狗@ 1fae3c6]
[狗@ a981ca,狗@ 8814e9,狗@ 1503a3,狗@ 1a1c887,狗@ 743399,狗@ e7b241,狗@ 167d940,狗@ e83912,狗@ 1fae3c6]
最佳答案
您正在看到Object.toString
的Dog
表示形式,您需要重写该方法:
@Override
public String toString() {
return "Dog [Price=" + Price + ", Operator=" + Operator + "]";
}