引言:
今天群里有朋友問“怎么知道一個數(shù)組集合是否已經(jīng)存在當前對象”,大家都知道循環(huán)比對,包括我這位大神群友。還有沒其他辦法呢?且看此篇。
正文:
能找到這里的都是程序員吧,直接上代碼應該更清楚些。
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) { // data segment 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"); // <- data segment // 1, 字符串數(shù)組是否存在子元素 // 1-1, 直接使用API Arrays.sort(SAMPLE_ARRAY); int index = Arrays.binarySearch(SAMPLE_ARRAY, TEST_STR); System.out.println("1-1_sort-binarySearche:" + ((index != -1) ? true : false)); // 1-2, 使用正則(因Arrays.toString()引入了“, [ ]”故只在有限環(huán)境下可靠) 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()); // 1-3, 都會寫循環(huán),略過。 // TODO: 循環(huán)數(shù)據(jù)依次比對,此處略去5行代碼。 // 2, 集合是否存在子元素 // 2-1, 最常用的contains System.out.println("2-1_contains:" + TEMPLATE_COLL.contains(TEST_STR)); // 2-1-1, 擴展: // 按模板集合,將當前集合分為“模板已存在”與“不存在”兩個子集。 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)數(shù)組至少三種:
A)binarySearch(,)。但條件是需要事先排序,開銷需要考慮。
B)Regex。但需要將數(shù)組轉為字符串,Arrays類提供的方法會引入“, [ ]”這三種分割符,可能影響判定結果。
C)循環(huán)比對。
2)集合至少兩種:
A)循環(huán)。如果只是判定默認存在(非定制型存在),建議直接不考慮。
B)contains。能靠過來就果斷靠吧。
3)集合提供了類似“加減”的運算,可以留意一下。
以上就是小編為大家?guī)淼膉ava判定數(shù)組或集合是否存在某個元素的實例全部內容了,希望大家多多支持武林網(wǎng)~
新聞熱點
疑難解答