Help with arrays
Hi what i am having problems with arrays.
I have an array of, for now 10 string objects, and a second array containing the same objects. What i want to do is compare them and anywhere an object in the first array appears more than once in the second array i want to remove, it so that each object only occurs one time in the second array.
I have an idea how this could be done, take a for loop which iterates through all elements in the first array, and inside that a second loop that takes the first element of that array and compares it to each element in the second array, and so on for each element in the array. I just dont know how to implement this in java, or how to remove the duplicate entries from the second array, can anyone help it would be greatly appreciated!
Thanks
Just if this is any help, what i am doing at the moment is this:
for(int i = 0, n = words.length; i<n; i++) {
totalWords++;
for(int j = i+1, m = array1.length; j < m; j++){
if(words[i].equals(array1[j])){
System.out.println("match :" + words[i]);
Since i dont know how to remove an element from the array i have just been printing out where a duplicate word is found, however if a word appears more than 3 times in the array then it outputs "match" for that word an incorrect number of times... can anybody see why?
[1415 byte] By [
cupanTae] at [2007-11-11 7:40:35]

# 1 Re: Help with arrays
It would be alot easier to use ArrayLists if you need to remove elements. Otherwise you would have to create a new array each time you remove an element. You could use a method like this if you really need to use regular arrays...(homework??)
public static String [] remove(String [] arr, int index){
if(index < 0 || index >= arr.length){
return null;
}
String [] arr2 = new String[arr.length - 1];
for(int i = 0, j = 0; i < arr.length && j < arr2.length; ++i){
if(i != index){
arr2[j++] = arr[i];
}
}
return arr2;
}
# 3 Re: Help with arrays
Would it make sense to only add to the second array if you do not find the current element in the first array in the second array? Here is pseudocode for an possible approach to this
foreach ( element : array1 )
{
search array2 for array1.currentElement;
if (notFound)
{
array2.add( array1.currentElement );
}
}
nspils at 2007-11-11 22:39:47 >

# 4 Re: Help with arrays
It would be alot easier to use ArrayLists if you need to remove elements.
Definitely, whenever you are dealing with an object/valuegroup of which you don't know how many you will be getting, then Java is packed with tools for handling that (vector, arraylist, set...). Using arrays for this is reserved for those who enjoy pain and those who have to do it as part of their education.
sjalle at 2007-11-11 22:40:46 >
