Is This Java Code Correct for Comparing Array Elements?

  • Context: Java 
  • Thread starter Thread starter courtrigrad
  • Start date Start date
  • Tags Tags
    Java
Click For Summary

Discussion Overview

The discussion revolves around the correctness of a Java code snippet intended to compare elements of two arrays. Participants explore various interpretations of the function's purpose, which is to determine whether the arrays are different or if elements from one array exist in another. The scope includes technical explanations, code corrections, and conceptual clarifications.

Discussion Character

  • Technical explanation
  • Debate/contested
  • Conceptual clarification

Main Points Raised

  • Some participants assert that the original code correctly checks if the arrays are different, while others argue it does not fulfill the intended purpose of checking for common elements.
  • One participant suggests changing the inequality operator from != to == to achieve the desired functionality, while another counters that this would not work as intended.
  • There is a proposal to rename the function to better reflect its purpose, suggesting names like 'isSubsetOf' or 'isContainedIn'.
  • A later reply provides an alternative code snippet that checks if all elements of one array are present in the other, indicating a different approach to the problem.
  • Participants discuss the implications of using the .equals() method for array comparison, noting that it does not function as expected for primitive arrays.

Areas of Agreement / Disagreement

Participants express differing views on the correctness of the original code and its intended functionality. There is no consensus on the best approach to achieve the desired outcome, and multiple competing views remain regarding the implementation details.

Contextual Notes

Some participants mention the importance of array length checks and the need for clarity in function naming to avoid confusion about the function's purpose. There are unresolved discussions about the implications of changing operators and the overall logic of the code.

Who May Find This Useful

Readers interested in Java programming, array manipulation, and code debugging may find this discussion relevant.

courtrigrad
Messages
1,236
Reaction score
2
Code:
 public class check
{
    public boolean isDifferent(int [] a, int [] b)
    {
     for(int i=0; i < a.length; i++)    //loop through your a array
    { 
        for(int j=0;j<b.length;j++)     //next loop through your b array
        {
            if( a[i] != b[j] )  // check for inequality
            {  
                return true;
            }
        } 
   }

   return false;
}
    }

is this correct?
 
Technology news on Phys.org
Yes it is, except that you'd have to use a.length() and b.length(). I have just a comment, that it might be better practice to capitalize class names. Use Check instead of check.
 
Errr. Probably not.
Your code checks A[n] = B[0->n] for all n in A.
I doubt that that was your intent.
The only way you could get false is if all elements had the same value.
 
Last edited:
how would i correct it?
 
courtrigrad said:
how would i correct it?
What are you trying to do?
 
i am trying to return true if any elemtns in a are in b and false if it is not
 
courtrigrad said:
i am trying to return true if any elemtns in a are in b and false if it is not
Change != to ==
 
NoTime said:
Change != to ==
No, the function isDifferent() returns true when the two arrays are different, so the code is correct.
 
ramollari said:
No, the function isDifferent() returns true when the two arrays are different, so the code is correct.
courtrigrad said:
i am trying to return true if any elemtns in a are in b and false if it is not
The OPs desired results seem different than what you say :confused:
 
  • #10
first of all,
the function is named as isDifferent()
which means it is supposed to check whether the arrays are different or not ... in which case the program is correct.

Even if it were supposed to check whether the arrays are same (if it is so , please change the name to isSame() to avoid confusion) , it is not right to change != to == since it might simply check the first element and if they are equal it will return which is not correct ... infact u have to exchange return true and return false ... that's all ...

-- AI
 
  • #11
no i think it would work, i just tested it
 
  • #12
It will always return true, unless the arrays a[] and b[] are both degenerate, and to most intents and purposes, useless.

Imagine a[0] = 3, then unless b[0] == 3, b[1] == 3, b[2] == 3, etc., the function will return true.

If all the elements of b[] are equal to 3, the function next checks a[1] against b[0] (which we already know is 3) so unless a[1] == 3 the function returns true, and so on.

So unless all the elements of both a[] and b[] contain exactly the same value (the number '3' in my example) the function returns true.

If you really want to know if the arrays a[] and b[] are different to each other, you need to write a different function.
 
  • #13
Here's a better version, though I've not tested it.

Code:
 public class check
{
    public boolean isDifferent(int[] a, int[] b)
    {
        if (a.length() != b.length()) return true;

        for (int i = 0; i < a.length(); i++)    //loop through your a array 
            if (a[i] != b[i])  // check for inequality
                return true;

        return false; // returns false if both arrays are same length and all elements match
    }
}
 
  • #14
There's an easier way!

The way you're doing it would work, too, though.

Now, assuming that the .equals() method works like I think it should for int[], you could simply have one line.

return !(a.equals(b));

if not, though, I would use something like ceptimus's code, except it is ".length" and not ".length()".
 
  • #15
The Idiot,
no that won't work either.

int a[] = {1,2,3};
int b[] = {1,2,3};
System.out.println(a.equals(b));
This will print false...
Similarly,
int a[] = {1,2,3};
int b[] = {1,3,4};
System.out.println(a.equals(b));
This also will print false...

However,
int a[] = {1,2,3};
int b[];
b=a;
System.out.println(a.equals(b));
This will print true ...

Can u see what it is doing?

Back to the problem,
If we note carefully , ceptimus has the same program as courtrigrad had except he added the vital condition of equal lengths to it...

courtrigrad,
replacing != with == would not work

If a = {1,2,3} and b={1,3,4}
replacing != with == will give true whereas it should be false.

The only way of achieving the "isSame()" function is exchanging the positions of return true and return false.

-- AI
P.S -> yes it is a.length and not a.length() as The Idiot mentions. (No pun intended :biggrin: )
 
Last edited:
  • #16
TenaliRaman said:
The Idiot,
no that won't work either.

int a[] = {1,2,3};
int b[] = {1,2,3};
System.out.println(a.equals(b));
This will print false...
Similarly,
int a[] = {1,2,3};
int b[] = {1,3,4};
System.out.println(a.equals(b));
This also will print false...

However,
int a[] = {1,2,3};
int b[];
b=a;
System.out.println(a.equals(b));
This will print true ...

Can u see what it is doing?

...Which is why I said "assuming it works the way I think it should."
 
  • #17
Arent u glad u got it cleared? :wink:

-- AI
Its always good to stand on one side and say this grass is greener than to stand on the fence and decide which grass is greener.
 
  • #18
guys thanks for the help but i think this is not what i was looking for. the program returns true if all of the elements in the first array are in the second array regardless of order.


Example

{1,2,3}
{3,2,1,5,6,7}

returns true


{1,2,3}
{3,6,4,8}
returns false

how wouls i then fix the program??

thanks
 
  • #19
Why are you calling the function, 'isDifferent'? Shouldn't it be called 'isaSubsetOf', or 'isContainedIn' if that's what you want it to do.
 
  • #20
yes, sorry, its just a generic method name...
 
  • #21
So, the array "a" needs to have all its elements in array "b"?

How about something like this?

Code:
for(int i = 0; i<a.length; i++)
{
     int j;
     for(j = 0; j<b.length; j++)
     {
          if(a[i] == b[j])
               break;
     }
     if(j == b.length) //a[i] was not found in b.
          return false;
}

return true; //all values were successfully found.
 

Similar threads

Replies
8
Views
3K
  • · Replies 13 ·
Replies
13
Views
4K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 25 ·
Replies
25
Views
3K
  • · Replies 3 ·
Replies
3
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 7 ·
Replies
7
Views
2K