黑马程序员技术交流社区
标题:
泛型中的问题
[打印本页]
作者:
青菜白汤
时间:
2013-12-27 12:26
标题:
泛型中的问题
这个问题是要求在中间没加泛型的加下泛型,自己定义的排序, 全给加上泛型, 让编译时别出来那些因为泛型的警告
复制代码
/*
*先按照姓排,姓相同就按名排序
*
*/
import java.util.*;
class TComp implements Comparator
{
public int compare(Object a, Object b) {
int i, j, k;
String aStr, bStr;
aStr = (String) a;
bStr = (String) b;
i = aStr.lastIndexOf(" ");
j = bStr.lastIndexOf(" ");
k = aStr.substring(i).compareTo(bStr.substring(j));
if (k==0)
{
return aStr.compareTo(bStr);
}
else return k;
}
}
public class DemoMapComparator{
public static void main(String[] args) {
TreeMap<String, Double> tm = new TreeMap<String, Double>(new TComp());
tm.put("JW Wang", 2000.2);
tm.put("JP Huang", 20.13);
tm.put("Min Huang", 300.25);
System.out.println(tm);
Set st = tm.entrySet();
System.out.println(st);
Iterator i = st.iterator();
while (i.hasNext())
{
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
double d = ((Double)tm.get("JP Huang")).doubleValue();
tm.put("JP Huang", d + 1000);
System.out.println("JP Huang's new balance: " + tm.get("JP Huang"));
}
}
作者:
松毛
时间:
2013-12-27 13:42
这是我添加的,你看一下符不符合你的要求。
import java.util.*;
class TComp implements Comparator<Object>
{
public int compare(Object a, Object b) {
int i, j, k;
String aStr, bStr;
aStr = (String) a;
bStr = (String) b;
i = aStr.lastIndexOf(" ");
j = bStr.lastIndexOf(" ");
k = aStr.substring(i).compareTo(bStr.substring(j));
if (k==0)
{
return aStr.compareTo(bStr);
}
else return k;
}
}
public class DemoMapComparator{
public static void main(String[] args) {
TreeMap<String, Double> tm = new TreeMap<String, Double>(new TComp());
tm.put("JW Wang", 2000.2);
tm.put("JP Huang", 20.13);
tm.put("Min Huang", 300.25);
System.out.println(tm);
Set<Map.Entry<String,Double>> st = tm.entrySet();
System.out.println(st);
Iterator<Map.Entry<String,Double>> i = st.iterator();
while (i.hasNext())
{
Map.Entry<String,Double> me = (Map.Entry<String,Double>)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
double d = ((Double)tm.get("JP Huang")).doubleValue();
tm.put("JP Huang", d + 1000);
System.out.println("JP Huang's new balance: " + tm.get("JP Huang"));
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2