0

I'm writing a method where it take an array, checks to see if the negative value of an element in the array is present, if it is, then it returns both the value(positive and negative).

I'm coming from python, where you can use if i is in n, but I don't see any similar methods with Jave. I've read around and saw there are more than one method, but they require over 6+ lines of code.. I was wondering if there was a shorter way for something this simple?

My planned algorithm is to take i in a(the array), multiply i*-1 = x.
if x is in the array, then it adds it to an Arraylist that returns at the end of the for loop

Amir Naghizadeh
  • 383
  • 3
  • 14
user1730056
  • 623
  • 3
  • 11
  • 19
  • if i is in n (lookup i in array n?) --> can't be done directly apart from looping.. however you could do Arrays.asList(n).contains(i) – Scorpion Nov 26 '12 at 11:44

3 Answers3

1

You can use Arrays.binarySearch method (Arrays an calass with help methods to work with array)

Important: Array must bu sorted before using this method! It could be done by Arrays.sort(yourArray)

So your code will look like this

int index = Arrays.binarySearch(inArray, valueToFind)
//do smth with index or get item by index

Hope this will help you...

nkukhar
  • 1,975
  • 2
  • 18
  • 37
1

To find an element in the array:

Arrays.asList(myArray).contains(myElement);

Note that this will only work for non-primitive arrays. For primitives, you are better off using a for-each loop:

int myElement = 12;
for(int myArrayElement : myArray) {
    if(myElement == myArrayElement) {
        // ...
    }
}

And to reverse an integer to become negative:

int myElement = 123;
myElement = -myElement; // it is now -123
Phil K
  • 4,939
  • 6
  • 31
  • 56
0

Java has support for a kind of foreach: http://www.leepoint.net/notes-java/flow/loops/foreach.html

for (type var : arr) {
    body-of-loop, use 'var' for element
}

Also, arrays have an index, you could use:

int i = 0;
for (i = 0; i < array.length; i++) {
   body-of-loop, use array[i] for element
}
Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195