Search code examples
javaarraysunique

How to check an array on runtime if contains certain value


The code provided below do a task that it gets all the x and y or like strings, and adds it to array.

I can add them all to array but what I want is to check that if the variable that I am about to insert into an array already exists then do not insert else insert.

ArrayList vars = new ArrayList();
for(int i = 0; i < temp.length; i++)
    for(int j = 1; j < temp[0].length - 1; j++)
    {
        String text_to_parse = temp[i][j];
        Pattern y = Pattern.compile("[?]\\w[,)]"); // find the values in pattern of ?x, or ?x)
        Matcher z = y.matcher(text_to_parse);
        while(z.find())
        {
            String to_add = z.group();
            to_add = to_add.replaceAll("[\\,\\) ]","");
            // logic required here if to_add exist in vars then do no insert else insert

        }
     }

I tried using vars.contain but it adds all the values that it finds.


Solution

  • Try if vars does not contain. Like so using the ! operator

    if (!(vars.contains(item)))
       //add the item
    else
       //do nothing