java斷定數組或集合是否存在某個元素

引言:  

  今天羣裏有朋友問「怎麼知道一個數組集合是否已經存在當前對象」,你們都知道循環比對,包括我這位大神羣友。還有沒其餘辦法呢?且看此篇。 

正文:  

  能找到這裏的都是程序員吧,直接上代碼應該更清楚些。 

Java代碼   收藏代碼
  1. import java.io.Serializable;  
  2. import java.util.ArrayList;  
  3. import java.util.Arrays;  
  4. import java.util.Collection;  
  5. import java.util.regex.Matcher;  
  6. import java.util.regex.Pattern;  
  7.   
  8. public class Test implements Serializable {  
  9.   
  10.     private static final long serialVersionUID = 2640934692335200272L;  
  11.   
  12.     public static void main(String[] args) {  
  13.   
  14.         // data segment  
  15.         String[] SAMPLE_ARRAY = new String[] { "aaa""solo""king" };  
  16.         String TEST_STR = "king";  
  17.         Collection TEMPLATE_COLL = new ArrayList();  
  18.         TEMPLATE_COLL.add("aaa");  
  19.         TEMPLATE_COLL.add("solo");  
  20.         TEMPLATE_COLL.add("king");  
  21.         // <- data segment  
  22.   
  23.         // 1, 字符串數組是否存在子元素  
  24.         // 1-1, 直接使用API  
  25.         Arrays.sort(SAMPLE_ARRAY);  
  26.         int index = Arrays.binarySearch(SAMPLE_ARRAY, TEST_STR);  
  27.         System.out.println("1-1_sort-binarySearche:"  
  28.                 + ((index != -1) ? true : false));  
  29.   
  30.         // 1-2, 使用正則(因Arrays.toString()引入了「, [ ]」故只在有限環境下可靠)  
  31.         String tmp = Arrays.toString(SAMPLE_ARRAY);  
  32.         Pattern p = Pattern.compile("king");  
  33.         Matcher m = p.matcher(tmp);  
  34.         System.out.println("1-2_toString-Regex:" + m.find());  
  35.   
  36.         // 1-3, 都會寫循環,略過。  
  37.         // TODO: 循環數據依次比對,此處略去5行代碼。  
  38.   
  39.         // 2, 集合是否存在子元素  
  40.         // 2-1, 最經常使用的contains  
  41.         System.out.println("2-1_contains:" + TEMPLATE_COLL.contains(TEST_STR));  
  42.   
  43.         // 2-1-1, 擴展:  
  44.         // 按模板集合,將當前集合分爲「模板已存在」與「不存在」兩個子集。  
  45.         Collection coll = new ArrayList<String>();  
  46.         coll.add("aaa");  
  47.         coll.add("bbb");  
  48.         coll.add("ccc");  
  49.         // 完整複製集合  
  50.         Collection collExists = new ArrayList(coll);  
  51.         Collection collNotExists = new ArrayList(coll);  
  52.   
  53.         collExists.removeAll(TEMPLATE_COLL);  
  54.         System.out.println("2-1-1_removeAll[exist]:" + collExists);  
  55.         collNotExists.removeAll(collExists);  
  56.         System.out.println("2-1-1_removeAll[notexist]:" + collNotExists);  
  57.   
  58.     }  
  59.   
  60. }  

  運行結果: 
Java代碼   收藏代碼
  1. 1-1_sort-binarySearche:true  
  2. 1-2_toString-Regex:true  
  3. 2-1_contains:true  
  4. 2-1-1_removeAll[exist]:[bbb, ccc]  
  5. 2-1-1_removeAll[notexist]:[aaa]  


  小結一下吧~。= 

  1)數組至少三種: 
    A)binarySearch(,)。但條件是須要事先排序,開銷須要考慮。 
    B)Regex。但須要將數組轉爲字符串,Arrays類提供的方法會引入「, [ ]」這三種分割符,可能影響斷定結果。 
    C)循環比對。 

  2)集合至少兩種: 
    A)循環。若是隻是斷定默認存在(非定製型存在),建議直接不考慮。 
    B)contains。能靠過來就果斷靠吧。 

  3)集合提供了相似「加減」的運算,能夠留意一下。