2
node_marked_array.add(strings[0]);

for (int i = 0; i < strings.length; i++) {
    for (int a = 0; a < strings2.length; a = a + 2) {
        if (node_marked_array.get(i).equals(strings2[a])) {
            if (!node_marked_array.get(i).equals(strings2[a + 1])) {
                //    System.out.println("marked node: " + node_marked_array.get(i) + "=" + strings2[a] + ", added node " + strings2[a+1]);
                node_marked_array.add(strings2[a + 1]);
            }
        }
    }
}

I have an array named strings2 of elements each being:

1, 2, 1, 3, 2, 3, 2, 4, 3, 2, 5, 5, 2,

and my code is supposed to go through the array and if it matches for example any of the element that is in the array called strings: {1,2,3,4,5} with that of strings2 for each even element. It checks the i+1 element of the array above to see if the element is already added to the marked array, if it isn't then it adds it. However I am seeing duplicate values even with

if (!node_marked_array.get(i).equals(strings2[a + 1]))

output: 1 2 3 3 4 2 5 2 5 5

2
  • Add some System.out.println() statements and see where your code is failing. Commented Dec 4, 2012 at 19:48
  • Unless this is an assignment, an easy way is just to convert this to a set: Set<T> mySet = new HashSet<T>(Arrays.asList(someArray)); Commented Dec 4, 2012 at 19:49

2 Answers 2

8

Use Set. Array is the wrong data type for this problem.

It contains a .toArray() method that will give you back an array after you've constructed the set, if that is what you require.

Sign up to request clarification or add additional context in comments.

Comments

4

Use a Set. Starting from your code:

HashSet<String> noDuplicate = new HashSet<String>();
for(int i=0;i<strings.length;i++)
{
  for(int a=0;a<strings2.length;a++)
  {
    if(strings[i].equals(strings2[a]))
    {
      noDuplicate.add(strings[i]);
    }
  }
}

// And then if you need an array:
String[] noDupArray = new String[noDuplicate.size()];
noDuplicate.toArray(noDupArray);

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.