有10个U盘,有两个重要的属性,即价格和容量,编写一个应用程序,
使用TreeMap<K,V>类,分别按价格和容量排序输出10个U盘的详细信息
趁你不注意直接上代码
import java.util.*;
public class Demo2 {
public static void main(String[] args) {
System.out.println("对价格进行排序:");
TreeMap<UP, String> up = new TreeMap<>(new MyComparator1());
up.put(new UP("32G", 64), "1");
up.put(new UP("16G", 39), "2");
up.put(new UP("64G", 89), "3");
up.put(new UP("8G", 59), "4");
up.put(new UP("16G", 49), "5");
up.put(new UP("32G", 99), "6");
up.put(new UP("64G", 119), "7");
up.put(new UP("32G", 159), "8");
up.put(new UP("16G", 69), "9");
up.put(new UP("64G", 216), "10");
Set<Map.Entry<UP, String>> entrySet = up.entrySet(); //keySet() : 迭代后只能通过get()取key;再根据key值取value,只能对一个(key或者value)遍历
//entrySet():迭代后可以e.getKey(),e.getValue()取key和value。
for (Map.Entry<UP, String> next : entrySet) {
UP key = next.getKey();
String value = next.getValue();
System.out.println(key + "是" + value + "号U盘");
}
System.out.println();
System.out.println("对容量进行排序:");
TreeMap<UP, String> up2 = new TreeMap<>(new MyComparator2());
up2.put(new UP("32G", 64), "1");
up2.put(new UP("16G", 39), "2");
up2.put(new UP("64G", 89), "3");
up2.put(new UP("08G", 59), "4");
up2.put(new UP("16G", 49), "5");
up2.put(new UP("32G", 99), "6");
up2.put(new UP("64G", 119), "7");
up2.put(new UP("32G", 159), "8");
up2.put(new UP("16G", 69), "9");
up2.put(new UP("64G", 216), "10");
Set<Map.Entry<UP, String>> entrySet2 = up2.entrySet(); //keySet() : 迭代后只能通过get()取key;再根据key值取value,只能对一个(key或者value)遍历
//entrySet():迭代后可以e.getKey(),e.getValue()取key和value。
Iterator<Map.Entry<UP, String>> it2 = entrySet2.iterator();
while (it2.hasNext()) {
Map.Entry<UP, String> next = it2.next();
UP key = next.getKey();
String value = next.getValue();
System.out.println(key + "是" + value+"号U盘");
}
}
}
class MyComparator1 implements Comparator<UP> {
@Override
public int compare(UP p1, UP p2) {
if (p1.getPrice() > p2.getPrice()) {
return -1;
} else if (p1.getPrice() < p2.getPrice()) {
return 1;
}
return 0;
}
}
class MyComparator2 implements Comparator<UP> {
@Override
public int compare(UP p1, UP p2) {
if (p1.getCapacity().compareTo(p2.getCapacity())>0) {
return -1;
} else if (p1.getCapacity().compareTo(p2.getCapacity())<=0) {
return 1;
}
return 0;
}
}
class UP implements Comparable<UP> {
private String capacity;
private int price;
public String getCapacity() {
return capacity;
}
public int getPrice() {
return price;
}
@Override
public int compareTo(UP p) {
if (this.capacity.compareTo(p.capacity)>0) {
return 1;
} else if (this.capacity.compareTo(p.capacity)<=0) {
return -1;
}
return 0;
}
@Override
public String toString() {
return "UP{" +
"容量为:'" + capacity +
",价格为:" + price +
'}';
}
public UP(String capacity, int price) {
this.capacity = capacity;
this.price = price;
}
}
TIPS!!:【新人发帖】以上代码仅作参考,由于compareTo方法只能比较两个字符串相同位置的ASCII码,如果把“08G”改为“8G”,在对容量进行排序的时候,这个8个G的u盘会直接爬到容量最高,这好吗,这不好,不过目前我也不知道怎么解决
(代码有点憨,希望有大佬能给出更好的解决方案)