try...catch大家都很熟悉吧,没错,就是判断代码是否会抛出异常,然后对其进行捕获,但是有没有想过,用try...catch当作if来使用呢?其实,仔细想想try...catch确实是按照if的流程来走的,只不过是没有else的if,来看个例子吧。
在使用try...catch以前的再做代码
- public Map getDataMap(String kind,PaginationSupport list){
- System.err.println(kind);
- SortedMap dataMap = new TreeMap();
- dataMap.put(0, "请选择");
- for(int i=0;i<list.getItems().size();i++){
- if("year".equals(kind)){
- dataMap.put(Integer.parseInt(((AppXzcf)list.getItems().get(i)).getSubYear()),((AppXzcf)list.getItems().get(i)).getSubYear());
- }else if("quarter".equals(kind)){
- dataMap.put(Integer.parseInt(((AppXzcf)list.getItems().get(i)).getSubJd()),((AppXzcf)list.getItems().get(i)).getSubJd());
- }
- }
- for (int i = 0; i < dataMap.size(); i++) {
- System.out.println(dataMap.get(DateUtil.getYear() - 5 + i));
- if(dataMap.get(DateUtil.getYear() - 5 + i+1)!=null&&dataMap.get(DateUtil.getYear() - 5 + i+1).equals(dataMap.get(DateUtil.getYear() - 5 + i))){
- System.out.println("===="+i);
- dataMap.remove(DateUtil.getYear() - 5 + i);
- }
- }
- return dataMap;
- }
- public Map getCityDataMap(String kind,PaginationSupport list){
- System.err.println(kind);
- SortedMap dataMap = new TreeMap();
- dataMap.put(0, "请选择");
- for(int i=0;i<list.getItems().size();i++){
- if("year".equals(kind)){
- dataMap.put(Integer.parseInt(((AppXzcfCollect)list.getItems().get(i)).getSubYear()),((AppXzcfCollect)list.getItems().get(i)).getSubYear());
- }else if("quarter".equals(kind)){
- dataMap.put(Integer.parseInt(((AppXzcfCollect)list.getItems().get(i)).getSubJd()),((AppXzcfCollect)list.getItems().get(i)).getSubJd());
- }
- }
- for (int i = 0; i < dataMap.size(); i++) {
- System.out.println(dataMap.get(DateUtil.getYear() - 5 + i));
- if(dataMap.get(DateUtil.getYear() - 5 + i+1)!=null&&dataMap.get(DateUtil.getYear() - 5 + i+1).equals(dataMap.get(DateUtil.getYear() - 5 + i))){
- System.out.println("===="+i);
- dataMap.remove(DateUtil.getYear() - 5 + i);
- }
- }
- return dataMap;
- }
看到了吗?再做代码只有几行是不一样的,其它的都是一样的,主要是这两个方法用到的是不同的实体类,如果要用到try...catch,会精简很多代码,如下
- public Map getDataMap(String kind,List list){
- SortedMap dataMap = new TreeMap();
- dataMap.put(0, "请选择");
- for(int i=0;i<list.size();i++){
- if("year".equals(kind)){
- try{
- dataMap.put(Integer.parseInt(((AppXzcf)list.get(i)).getSubYear()),((AppXzcf)list.get(i)).getSubYear());
- }catch (ClassCastException e) {
- dataMap.put(Integer.parseInt(((AppXzcfCollect)list.get(i)).getSubYear()),((AppXzcfCollect)list.get(i)).getSubYear());
- }
- }else if("quarter".equals(kind)){
- try{
- dataMap.put(Integer.parseInt(((AppXzcf)list.get(i)).getSubJd()),((AppXzcf)list.get(i)).getSubJd());
- }catch (ClassCastException e) {
- dataMap.put(Integer.parseInt(((AppXzcfCollect)list.get(i)).getSubJd()),((AppXzcfCollect)list.get(i)).getSubJd());
- }
- }
- }
看到了吧,这就是差别所在,try...catch不光可以用在ClassCastException中还可以用到其它很多类型这个实例的地方,去优化你的代码吧,这样才能使它更健壮,更美丽。
本文转自sucre03 51CTO博客,原文链接:http://blog.51cto.com/sucre/417178,如需转载请自行联系原作者