java斷定數組或集合是否存在某個元素
時間 2020-01-12
標籤
java
斷定
數組
集合
是否
存在
某個
元素
引言:
今天羣裏有朋友問「怎麼知道一個數組集合是否已經存在當前對象」,你們都知道循環比對,包括我這位大神羣友。還有沒其餘辦法呢?且看此篇。
正文:
能找到這裏的都是程序員吧,直接上代碼應該更清楚些。
- import java.io.Serializable;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.Collection;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
-
- public class Test implements Serializable {
-
- private static final long serialVersionUID = 2640934692335200272L;
-
- public static void main(String[] args) {
-
-
- String[] SAMPLE_ARRAY = new String[] { "aaa", "solo", "king" };
- String TEST_STR = "king";
- Collection TEMPLATE_COLL = new ArrayList();
- TEMPLATE_COLL.add("aaa");
- TEMPLATE_COLL.add("solo");
- TEMPLATE_COLL.add("king");
-
-
-
-
- Arrays.sort(SAMPLE_ARRAY);
- int index = Arrays.binarySearch(SAMPLE_ARRAY, TEST_STR);
- System.out.println("1-1_sort-binarySearche:"
- + ((index != -1) ? true : false));
-
-
- String tmp = Arrays.toString(SAMPLE_ARRAY);
- Pattern p = Pattern.compile("king");
- Matcher m = p.matcher(tmp);
- System.out.println("1-2_toString-Regex:" + m.find());
-
-
-
-
-
-
- System.out.println("2-1_contains:" + TEMPLATE_COLL.contains(TEST_STR));
-
-
-
- Collection coll = new ArrayList<String>();
- coll.add("aaa");
- coll.add("bbb");
- coll.add("ccc");
-
- Collection collExists = new ArrayList(coll);
- Collection collNotExists = new ArrayList(coll);
-
- collExists.removeAll(TEMPLATE_COLL);
- System.out.println("2-1-1_removeAll[exist]:" + collExists);
- collNotExists.removeAll(collExists);
- System.out.println("2-1-1_removeAll[notexist]:" + collNotExists);
-
- }
-
- }
運行結果:
- 1-1_sort-binarySearche:true
- 1-2_toString-Regex:true
- 2-1_contains:true
- 2-1-1_removeAll[exist]:[bbb, ccc]
- 2-1-1_removeAll[notexist]:[aaa]
小結一下吧~。=
1)數組至少三種:
A)binarySearch(,)。但條件是須要事先排序,開銷須要考慮。
B)Regex。但須要將數組轉爲字符串,Arrays類提供的方法會引入「, [ ]」這三種分割符,可能影響斷定結果。
C)循環比對。
2)集合至少兩種:
A)循環。若是隻是斷定默認存在(非定製型存在),建議直接不考慮。
B)contains。能靠過來就果斷靠吧。
3)集合提供了相似「加減」的運算,能夠留意一下。