GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes Array difference quantity Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Array difference quantity" Watch "Array difference quantity" New topic
Author

Array difference quantity

Ricko Jonesy
Greenhorn

Joined: Oct 09, 2008
Posts: 3
Hi everyone,

I have some trouble with an easy question.
I want to compare two arrays to check their difference quantity.
Here is my Example:

Array Server: 1,2,3,4,5,6,7,8
Array Client: 1,2,3,4,8

The difference quantity should be 5,6 and 7, right?.


I tried to get it with a function which compares the arrays to equality, but this did'nt work:


for ( int i = 0; i < Array2.length; i++ ) {
for (int value: Array2) {
if (Array2[i] == Array1[i]) {
System.out.println("Platz"+i+" stimmt");
}
else
{
System.out.println("Platz"+i+" stimmt nicht");
}
}
}


May anybody help me? Thank you!
Ankit Nagpal
Ranch Hand

Joined: Sep 09, 2008
Posts: 47

Hi,

What is the exact nature of problem:

1) Do you want to display those numbers in Array1 which aren't at the same index as Array2?

or

2) Do you want to display those numbers in Array1 which do not exist in Array2?
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19697
    
  20

Using Collections this would be quite easy. Check Arrays.asList, Collection.addAll and Collection.removeAll.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Ricko Jonesy
Greenhorn

Joined: Oct 09, 2008
Posts: 3
Rob: Could you please explain the procedure with the arraylists a bit closer?
So i have to add all of the Server-Array-Contents to one Arraylist and then subtract the contents of the Client-Array-Content via Collection.removeAll?

Thank you!
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19697
    
  20

That would be the trick yes. And because Collection.addAll and removeAll only accept other Collections, you need to convert the arrays to some Collection. And that's where my other suggestion can be used.

As said in the API of Set#removeAll:
If the specified collection is also a set, this operation effectively modifies this set so that its value is the asymmetric set difference of the two sets.

And that's just what you want.
Ricko Jonesy
Greenhorn

Joined: Oct 09, 2008
Posts: 3
thank you very mutch, it works perfect. more simple than expected.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19697
    
  20

Please note that if this is a homework question, your professor will most likely not approve that solution, since you're letting the API do the actual work.
 
GeeCON Prague 2014
 
subject: Array difference quantity