java determines whether an array or collection has an instance of an element

  • 2020-05-30 20:03:24
  • OfStack


Today, a friend in the group asked "how do I know if an array set has the current object?", everyone knows the loop comparison, including my friend in the group. Is there any other way? Look at this passage.


Can find here is the programmer, directly on the code should be more clear.

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(); 
    // <- data segment 
    // 1,  Whether there are child elements in the string array  
    // 1-1,  Direct use of API 
    int index = Arrays.binarySearch(SAMPLE_ARRAY, TEST_STR); 
        + ((index != -1) ? true : false)); 
    // 1-2,  Use regular (because Arrays.toString() The introduction of" , [ ] "So only in limited circumstances)  
    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,  I'm going to write the loop. Skip it.  
    // TODO:  The cyclic data are compared in sequence and omitted here 5 Lines of code.  
    // 2,  Whether the collection has child elements  
    // 2-1,  The most commonly used contains 
    System.out.println("2-1_contains:" + TEMPLATE_COLL.contains(TEST_STR)); 
    // 2-1-1,  extension : 
    //  According to the template set, the current set is divided into two subsets: "template exists" and "does not exist".  
    Collection coll = new ArrayList<String>(); 
    //  Fully replicated set  
    Collection collExists = new ArrayList(coll); 
    Collection collNotExists = new ArrayList(coll); 
    System.out.println("2-1-1_removeAll[exist]:" + collExists); 
    System.out.println("2-1-1_removeAll[notexist]:" + collNotExists); 

Operation results:

2-1-1_removeAll[exist]:[bbb, ccc] 

Summary 1 ~. =

1) at least 3 types of arrays:

A) binarySearch (,). But the condition is that you have to sort it in advance, and you have to think about the overhead.
Regex B). However, you need to convert the array to a string, and the method provided by Arrays class will introduce the three ", [] "delimiters, which may affect the decision result.
C) cyclic comparison.

2) at least two types of collections:

A) loop. If you just decide that the default exists (non-custom exists), it is recommended to ignore it directly.
contains B). If you can get over it, get over it.

3) the set provides operations similar to "addition and subtraction", so you can pay attention to 1.

Related articles: