数组的用法(转载)

                                                                                   数组的用法,经典

在编码过程中,数组是我们最最常用的数据结构之一。但是数组又是我们最容易抛弃的数据结构,经常由于初始化和数组长度固定等原因,我们常常用 ArrayList等其他一些集合类来代替它。其实,数组作为最简单的集合数据,与其他集合数据比较起来有操作简单和查询速度快等优点。对于其长度固定的弱点,也在很多时候可以得到相应的解决。此外,在编码过程中,有些是直观的就能让我们使用数组,而很多时候却不是那么直观,需要我们稍加分析才行。本文的总结,是对数组的使用的被忽略而又能显示数组优点的一些方面的阐述,希望用来抛砖引玉,引起大家对数组的用法进行挖掘。

第一,   数组对if…
else…和case语句的改进

在我们的编码过程中,if语句可以说是随处可见,我们将我们写的代码进行review的时候,经常能看到有一些很长的if…
else if…这样的语句很刺眼,但又好像无可奈何。

            
boolean flag = true;
            
switch(operatorId)
           
{
                
case 1:
                       conditionSql 
+= " > " + "'" + cond + "'";
                       
break;
                 
case 2:
                       conditionSql 
+= " >= " + "'" + cond + "'";
                       
break;
                 
case 3:
                       conditionSql 
+= " < " + "'" + cond + "'";
                       
break;
                 
case 4:
                       conditionSql 
+= " <= " + "'" + cond + "'";
                       
break;
                 
case 5:
                       conditionSql 
+= " = " + "'" + cond + "'";
                       
break;
                 
case 6:
                       conditionSql 
+= " like " + "'%" + cond + "%'";
                       
break;
                 
default:
                       flag 
= false;
                       
break;
           }


这是我择抄的一段case语句的代码,在代码的review过程中,我还发现过比这长多的很多这样的代码,所以这样的代码还是有一定的代表性。

我们来看这条语句:conditionSql 
+= " > " + "'" + cond + "'";很明显是一条重复性的语句。每个这样的语句的不同点在于前面的”>”,”>=”,”<”,”<=”,”=”等等,而他们对应的条件是1,23,4等等。我们一观察就可以知道,如果结果是一个数组的项的话,那么条件就是该数组的下标。看,多完美啊。

所以我们将上面的语句修改如下:

String[] conditionSqls 
= new String[]{">'",">='","<'","<='","='","like '%"};
       
boolean flag = true;
       
if(operatorId>=1&&operatorId<=6)
        
{
               conditionSql 
+= conditionSqls[operatorId-1]+cond+"'";
        }

        
else flag = false;
这样是不是简洁得多?

第二,   数组对大量重复性语句的改进

在编码过程中,我们经常会有这样的重复性语句:

request.setAttribute(
"getUserList", list);

                                   request.setAttribute(
"itemList", list);                

                                   request.setAttribute(
"tag1", tag);

                                   request.setAttribute(
"regularTotal",regularTotal);

                                   request.setAttribute(
"probationTotal",probationTotal);

                                   request.setAttribute(
"empTotal",empTotal);

                             request.setAttribute(
"deptEmpList",deptEmpList);

我们也遇到过这样的赋值语句:

String contractID 
= request.getParameter("contractID");

            String categoryID 
= request.getParameter("categoryID");

            String employeeID 
= request.getParameter("employeeID");

            String contractNumber 
= request.getParameter("contractNumber");

            String content 
= request.getParameter("content");

            String validityDate 
= request.getParameter("validityDate");

            String contractTerm 
= request.getParameter("contractTerm");

            String probationTime 
= request.getParameter("probationTime");

            String pay 
= request.getParameter("pay");

            String probationPay 
= request.getParameter("probationPay");

  String createDate 
= request.getParameter("createDate");

很明显,这样的语句都可以用数组来加以简化,我们先来看第一个,我们一看便知,request.setAttribute (
"getUserList", list);重复,而每一条语句的不同在于setAttribute的第一个参数和第二个参数不同。解决办法很明显,就是把一个参数和第二个参数都做数组:

String[] names 
= new String[]{“getUserList”,”itemList”,”tag1”,”regularTotal”,” probationTotal”,”empTotal”,”deptEmpList”};

Object[] values 
= new Object[]{list , list , tag , regularTotal , probationTotal , empTotal , deptEmpList };

For(
int I=0;I<names.length;I++)

{

       request.setAttribute(name[i],values[i]);

}


对于第二个语句,我们何必定义那么多的变量呢,不如用一个数组来代替他们?

 

第三,   互不相关的重复的判断语句

我们还遇到过大量重复的单条件判断语句,像下面这样的例子:

            
if(ObjectUtils.isNullOrEmpty(categoryID))
           
{
                 errors.add(ActionErrors.GLOBAL_ERROR,
                                  
new ActionError("ContractInfo.Add.categoryID"));
                 saveErrors(request, errors);
           }


            
if(ObjectUtils.isNullOrEmpty(employeeID))
           
{
                 errors.add(ActionErrors.GLOBAL_ERROR,
                                  
new ActionError("ContractInfo.Add.employeeID"));
                 saveErrors(request, errors);
           }


            
if(ObjectUtils.isNullOrEmpty(contractNumber))
           
{
                 errors.add(ActionErrors.GLOBAL_ERROR,
                                  
new ActionError("ContractInfo.Add.contractNumber"));
                 saveErrors(request, errors);
           }


            
if(ObjectUtils.isNullOrEmpty(validityDate))
           
{
                 errors.add(ActionErrors.GLOBAL_ERROR,
                                  
new ActionError("ContractInfo.Add.validityDate"));
                 saveErrors(request, errors);
           }


            
if(ObjectUtils.isNullOrEmpty(contractTerm))
           
{
                 errors.add(ActionErrors.GLOBAL_ERROR,
                                  
new ActionError("ContractInfo.Add.contractTerm"));
                 saveErrors(request, errors);
           }


            
if(ObjectUtils.isNullOrEmpty(probationTime))
           
{
                 errors.add(ActionErrors.GLOBAL_ERROR,
                                  
new ActionError("ContractInfo.Add.probationTime"));
                 saveErrors(request, errors);
           }


            
if(ObjectUtils.isNullOrEmpty(pay))
           
{
                 errors.add(ActionErrors.GLOBAL_ERROR,
                                  
new ActionError("ContractInfo.Add.pay"));
                 saveErrors(request, errors);
           }


            
if(ObjectUtils.isNullOrEmpty(probationPay))
           
{
                 errors.add(ActionErrors.GLOBAL_ERROR,
                                  
new ActionError("ContractInfo.Add.probationPay"));
                 saveErrors(request, errors);
           }


 
            
if(ObjectUtils.isNullOrEmpty(createDate))
           
{
                 errors.add(ActionErrors.GLOBAL_ERROR,
                                  
new ActionError("ContractInfo.Add.createDate"));
                 saveErrors(request, errors);
           }

  }

这种if语句没有else,每一个都要判断到,其实是一个循环语句。修改后的代码如下:

String[] values 
= newString[]{categoryID,employeeID,contractNumber,validityDate,contractTerm,probationTime,pay,probationPay,createDate};

String[] InfoNames 
= new String[]{“categoryID”,”employeeID”,”contractNumber”,”validityDate”,”contractTerm”,”probationTime”,”pay”,”probationPay”,”createDate”};

For(
int I=0;I<values.length;I++)
{
              
if(ObjectUtils.isNullOrEmpty(values[i]))
           
{
                 errors.add(ActionErrors.GLOBAL_ERROR,
                                  
new ActionError("ContractInfo.Add."+InfoNames[i]));
                 saveErrors(request, errors);
           }

}


第四,   零长度数组的使用。

在数组的使用过程中,我们经常出现这样的语句:

if(names!=null)

{
        
for(int I=0;I<names.length;I++
        
{
               ……
}


}


明明names是一个数组,却要判断它非空的情况,这个if语句让人感觉很多此一举,但又无可奈何。

其实,我们仔细一想,出现names为空的情况的原因就是在给names数组赋值的时候,出现了一种情况下没有对names初始化,这在我们的编码过程中其实是不允许的。

解决的办法就是在没有办法对names初始化的时候将它初始化为零长度数组。如:

String[] names;

        String condition 
= "1";

       
if(condition.equals("2"))
        
{
               names 
= new String[]{"name1","name2"};
        }

        
else
        
{
               names 
= new String[]{};
        }

        
for(int i=0;i<names.length;i++)
        
{
               System.out.println(names[i]);
        }


第五,   Arrays库的数组的用法。

在Java API的Arrays库里,有一些很好的方法,现列在下面:

1.  数组的查询:binarySearch

String[] strs1 
= new String[]{"1","2","3","4"};

  
int i = Arrays.binarySearch(strs1,"2");

  System.out.println(i);

2.  数组的覆盖:fill

String[] strs1 
= new String[]{"1","2","3","4"};

  Arrays.fill(strs1,
2,3,"haha");

  
for(int i=0;i<strs1.length;i++)

         
{

         System.out.println(strs1[i]);

         }


注意:第一个参数为数组,最后一个参数是覆盖后的新值,覆盖的位置为,从第二个参数开始,覆盖数组项的个数为,第三个参数减去第二个参数。

3.  数组的排序:sort

String[] strs1 
= new String[]{"1","2","6","4"};

Arrays.sort(strs1);

for(int i=0;i<strs1.length;i++)

        
{

        System.out.println(strs1[i]);

        }


第六,   数据和其他数据类型的转化

我们经常需要将数组转化为List、ArrayList等一些数据类型,然后我们又需要将他们转化回来。

将数组转化为List:

String[] strs1 
= new String[]{"1","2","6","4"};

        List list 
= Arrays.asList(strs1);

将数组转化为ArrayList:

String[] strs1 
= new String[]{"1","2","6","4"};

        List list 
= Arrays.asList(strs1);

       ArrayList al 
= new ArrayList();

       al.addAll(list);

将List转化为数组:

String[] strs1 
= new String[]{"1","2","6","4"};

        List list 
= Arrays.asList(strs1);

       String[] strs2 
= (String[])list.toArray(new String[0]);

        
for(int i=0;i<strs2.length;i++)

        
{

               System.out.println(strs1[i]);

        }


第七,   去掉数组中相同的项

我们知道,数组的项是可以重复的,有时候我们需要去掉数组中重复的项,怎么办?我们也知道,HashSet里面是没有重复的项的,我们可不可以将数组转化为HashSet,然后再转化回来呢?

String[] strs1 
= new String[]{"1","2","6","4","2","4"};

       HashSet set 
= new HashSet();

       set.addAll(Arrays.asList(strs1));

       String[] strs2 
= (String[])set.toArray(new String[0]);

        
for(int i=0;i<strs2.length;i++)

        
{

               System.out.println(strs1[i]);

        }


第八,   数组的复制

我们可以将一个数组的一些项复制到另外一个数组里面去,如:

String[] strs1 
= new String[]{"1","2","3","4","5","6"};

       String[] strs2 
= new String[4];

System.arraycopy(strs1,
2,strs2,0,2);

        
for(int i=0;i<strs2.length;i++)

        
{

        System.out.println(strs2[i]);

        }


上面的这段代码是将数组strs1复制到数组strs2里面去,从strs1的下标为2的项开始复制,复制到strs2下标为0的项开始,一直复制2项。

第九,   长度不定的数组

如果数组长度只有有限的几个选择,可以使用如下的方法:

String[] array;

if(length.equals(“4”))

{
        array 
= new String[4];
        ……
}


else if(length.equals(“9”))
{

        array 
= new String[9];
        ……
}


else if(length.equals(“10”))
{
        array 
= new String[10];
        ……
}

else array = new String[]{};

 

如果不是能有限确定的,则可以利用反射来生成数组,如:

try {

               
int length = 10;

               Class cls 
= Class.forName(

               
"java.lang.String");

               Object arr 
= Array.newInstance(cls, length);

               String[] strs 
= (String[])arr;

               
for(int i=0;i<strs.length;i++)

               
{
                      strs[i] 
= String.valueOf(i);
               }

               
for(int i=0;i<strs.length;i++)
               
{
                      System.out.println(strs[i]);
               }

               }

               
catch (Throwable e) {
               System.err.println(e);
               }

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值