Reputation: 1
I've got this code:
@Override
public int compareTo(LargeInt passedIn)//
{
if(passedIn == null)
{
throw new RuntimeException("NullExceptionError");
}
int ewu = 0;
int avs = 0;
if(this.myArray.length != passedIn.myArray.length)
{
return this.myArray.length - passedIn.myArray.length;
}
for(this.myArray.length == passedIn.myArray.length)
{
}
for(int x = 0; x < this.myArray.length; x++)
{
ewu += this.myArray[x];
}
for(int x = 0; x < passedIn.myArray.length; x++)
{
avs += passedIn.myArray[x];
}
return ewu - avs;
}
My goal is, under this line:
for(this.myArray.length == passedIn.myArray.length)
I want to If the lengths are equal, go through the array until a value that is different is found. Then subtract those two values and return. How might I go about doing this?
Upvotes: 0
Views: 63
Reputation: 63955
You can do
public int compareTo(LargeInt passedIn)
{
if (this.myArray.length != passedIn.myArray.length)
{
return this.myArray.length - passedIn.myArray.length;
}
for (int i = 0; i < this.myArray.length; i++) {
if (this.myArray[i] != passedIn.myArray[i])
return this.myArray[i] - passedIn.myArray[i];
}
return 0;
}
If the arrays are different lengths you've returned already. There is no point in checking whether they are the same length. And after you've checked for differences in the new loop, you can be sure that they are identical and skip those loops that sum up the arrays. They will have the same sum since they must be identical.
Upvotes: 1
Reputation: 1523
If the lengths are equal
so, why not use if(myArray.length == passedIn.myArray.length)
instead of that (syntactically incorrect) for
-loop? (In your case, it is just the else
of the condition before).
If the condition is true
, iterate over the arrays as you did by the loops below.
Upvotes: 0