gpt4 book ai didi

java - 填充复杂的 Map 并访问其值

转载 作者:行者123 更新时间:2023-12-02 00:02:41 25 4
gpt4 key购买 nike

问题1:我想将以下“Class Dog”的“特定”排序值添加到“Ser”类中使用的“Map”中。但我不知道如何实现这一点,

问题2:如果成功填充,如何访问 map 的填充值

以下是我绝望的尝试。

 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

map 值的输出:[狗@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]

最佳答案

您看到 DogObject.toString 表示形式,您需要重写该方法:

@Override
public String toString() {
return "Dog [Price=" + Price + ", Operator=" + Operator + "]";
}

关于java - 填充复杂的 Map 并访问其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14509445/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com