1

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.

3
  • Is it really important to keep the sequence of string as encountered? Otherwise it would prove useful to change varsto be an implementation of java.util.Set (e.g. java.util.HashSet). This will provide way better performance on .contains(). This might not get obvious with some few entries to be managed, but getting used to using the appropriate data structures will help a lot in general. (For large sets of entries you might even consider using a Set for easy detecting of pre-existence and a List implementation for keeping ordering.) Commented May 19, 2016 at 5:38
  • And BTW: please use interface types with your variables not hardcoded implementations. In your case you might write: List vars = new ArryList() Commented May 19, 2016 at 5:40
  • @rbento thanks for editing but actually the ?x and ?y are followed by the question marks as provided earlier, the question mark indicates that next is variable coming in the string. Commented May 19, 2016 at 6:15

1 Answer 1

1

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

if (!(vars.contains(item)))
   //add the item
else
   //do nothing
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.