Java 获取元素在数组中的位置

Java 中如何获取元素在数组中的位置呢?

(1)

Java代码  Java 获取元素在数组中的位置
  1. /*** 
  2.      * Get location of element in a array 
  3.      * @param arr : a array 
  4.      * @param value2 : element of array 
  5.      * @return 
  6.      */  
  7.     public static int indexOfArr(String[] arr,String value2){  
  8.         if(ValueWidget.isNullOrEmpty(arr)){  
  9.             return SystemHWUtil.NEGATIVE_ONE;  
  10.         }  
  11.         for(int i=0;i<arr.length;i++){  
  12.             if(arr[i].equals(value2)){  
  13.                 return i;  
  14.             }else{//做了容错,不是完全匹配  
  15.                 if(value2.startsWith(arr[i])){  
  16.                     return i;  
  17.                 }  
  18.             }  
  19.         }  
  20.         return SystemHWUtil.NEGATIVE_ONE;  
  21.     }  

 
Java 获取元素在数组中的位置
 测试:

Java代码  Java 获取元素在数组中的位置
  1. @Test  
  2.     public void test_indexOf(){  
  3.         String[]arr=new String[]{"a","b","c","d"};  
  4. //      System.out.println(SystemHWUtil.indexOfArr(arr, "d"));  
  5.         org.junit.Assert.assertEquals(3, SystemHWUtil.indexOfArr(arr, "d"));  
  6.     }  

 注意:位置是从零开始的.

(2)

Java代码  Java 获取元素在数组中的位置
  1. /*** 
  2.      * times byte occure int byte[] 
  3.      *  
  4.      * @param hexStr 
  5.      * @param keyWord 
  6.      * @return 
  7.      */  
  8.     public static int indexOf(String hexStr, String keyWord) {  
  9.         return hexStr.indexOf(keyWord.toLowerCase()) / 2;  
  10.     }  
  11.   
  12.     public static int indexOf(byte[] bytes, String keyWord) {  
  13.         return indexOf(SystemHWUtil.toHexString(bytes), keyWord.toLowerCase());  
  14.     }  
  15.   
  16.     public static int indexOf(byte[] bytes, byte[] keyWord) {  
  17.         return indexOf(SystemHWUtil.toHexString(bytes), SystemHWUtil  
  18.                 .toHexString(keyWord).toLowerCase());  
  19.     }