0

I need some help with Java code.

I have an array of 10 elements. I want to compare the first element, ie. array[0] to array[1], array[2], ... array[9]. If I find any elements that are equal to array[0] then I perform some actions. I then need to compare array[1] to array[2], array[3],...array[9] and find if array[1] is equal to something and so on. I really can't figure this out, and I am stuck. Can someone help me.

cdn
  • 61
  • 1
  • 1
  • 5
  • 1
    please see if this answer can help you : http://stackoverflow.com/questions/840781/easiest-way-to-find-duplicate-values-in-a-javascript-array – Aaike Feb 17 '12 at 01:04

4 Answers4

5

So to compare to all other elements, start at the next and work up:

int i = x; //set i to the array index to compare against
for(int j = i + 1; j < array.length; j++){
    if(array[i].equals(array[j]))
        ...;
}

If you want to go through the whole list like this, you can do a nested for:

for(int i = 0; i < array.length; i++){
    for(int j = i + 1; j < array.length; j++){
        if(array[i].equals(array[j]))
            ...;
    }
}
Ryan Amos
  • 5,422
  • 4
  • 36
  • 56
1

I would use ArrayList and then you could use the contains method to see if the List contains() your item.

Java Example

package org.kodejava.example.util;

import java.util.ArrayList;
import java.util.List;

public class ArrayListContains {
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        list.add("Item 1");
        list.add("Item 2");
        list.add("Item 3");
        list.add("Item 4");

        if (list.contains("Item 1")) {
            System.out.println("True");
        } else {
            System.out.println("False");
        }
    }
}
Logan
  • 2,369
  • 19
  • 20
0

You can sort the array and make it easy for the for loop

Arrays.sort(array);
for(int i = 0 ; i < array.length - 1; i++) {
    if(array[i].equals(array[i++])) {
      ........
      break();
    }
}
asela38
  • 4,546
  • 6
  • 25
  • 31
0
  1. Create a set to hold onto unique elements.
  2. Iterate over the array, attempting to add elements to the set.
  3. If an element is added to the set, this is the first time encountering the item.
  4. If an element is not added to the set, it is a duplicate item.

Some code for the above steps:

Set<Object> uniqueElements = new HashSet<Object>();
for (Object element : array) {
    if (!uniqueElements.add(element)) {
        // duplicate element; do your processing
    }
}
Brent Worden
  • 10,624
  • 7
  • 52
  • 57