Finding the Duplicate element

HiI have an array with numbers 1--100.Once again i have inserted one more element ( the value which is already in the 1100 series) as 101 element.I need to find out that duplicate element.pls help me.Thanks in Advanceur'smalli
[283 byte] By [malli_mcachia] at [2007-10-3 3:56:14]
# 1

Why do you use an array?

Instead use the collections java provides.

// I didn't use Autoboxing to make things clear

ArrayList<Integer> integerList = new ArrayList<Integer>();

// add 100 elements here

Integer int_element;

for (int i = 1; i<=100; i++) {

int_element = new Integer(i);

integerList.add( int_element );

}

// f.e. test if 55 is in the array

Integer testInt = new Integer(55);

if integerList.contains( testInt ) {

// found

}

else {

// not found

}

The method contains of ArrayList checks via method equals of the class Integer, if there is an appropiate element.

Internally (if you dare a look into the java source) this should be something like:

class ArrayList() {

public boolean contains(Object o) {

Iterator<Integer> it = this.iterator();

while ( it.hasNext() ) {

if (o.equals( it.next() ) ) {

return true;

}

}

return false;

}

}

Remark for correctness: the contains method of ArrayList uses indexOf(Object o), but indexOf does something similar to the above!

DoodleTheNoodlea at 2007-7-14 21:54:25 > top of Java-index,Core,Core APIs...
# 2
Further remark:if you want to avoid duplicate elements, you could use Set or subtypes thereof.For further details see Java Collections Framework Tutorial: http://java.sun.com/docs/books/tutorial/collections/index.html
DoodleTheNoodlea at 2007-7-14 21:54:25 > top of Java-index,Core,Core APIs...