泛型与集合实验
有10名员工,其属性有工号和工资。编写一个程序,使用TreeMap<K,V>,分别按照工号和工资排序输出所有员工的信息。
提示:TreeMap<K,V>以下两个成员方法可供使用:
public Set
keySet() Returns a Set view of the keys contained in this map. The set's iterator returns the keys in ascending order.
public Collection
values() Returns a Collection view of the values contained in this map. The collection's iterator returns the values in ascending order of the corresponding keys.
import java.util.*;
class salary implements Comparable {
double key=0;
salary(double d) {
key=d;
}
public int compareTo(Object b) {
salary disc=(salary)b;
if((this.key-disc.key)==0)
return -1;
else
return (int)((this.key-disc.key)*1000);
}
}
class Number{
int number;
double price;
Number(int m,double e) {
number=m;
price=e;
}
}
public class t5 {
public static void main(String args[ ]) {
TreeMap<salary,Number> treemap= new TreeMap<salary,Number>();
int amount[]={12,23,15,17,24,19,22,18,20,25,10};
double price[]={40,20,10,80,30,22,38,32,25,16};
Number UDisc[]=new Number[10];
for(int k=0;k<UDisc.length;k++) {
UDisc[k]=new Number(amount[k],price[k]);
}
salary key[]=new salary[10];
for(int k=0;k<key.length;k++) {
key[k]=new salary(UDisc[k].number); }
for(int k=0;k<UDisc.length;k++) {
treemap.put(key[k],UDisc[k]); }
int number=treemap.size();
Collection<Number> collection=treemap.values();
Iterator<Number> iter=collection.iterator();
System.out.println("按照工号排列:");
System.out.println("工号"+" "+"工资");
while(iter.hasNext()) {
Number disc=iter.next();
System.out.println(+disc.number+" "+disc.price+"千元"); }
treemap.clear();
for(int k=0;k<key.length;k++) {
key[k]=new salary(UDisc[k].price); }
for(int k=0;k<UDisc.length;k++) {
treemap.put(key[k],UDisc[k]); }
number=treemap.size();
collection=treemap.values();
iter=collection.iterator();
System.out.println("按照工资排列:");
System.out.println("工资"+" "+"工号");
while(iter.hasNext()) {
Number disc=iter.next();
System.out.println(disc.price+"千元"+" "+disc.number);
}
}
}