Skip to Content
Java Coding Problems
book

Java Coding Problems

by Anghel Leonard
September 2019
Intermediate to advanced
816 pages
18h 47m
English
Packt Publishing
Content preview from Java Coding Problems

Check only for the presence

Let's assume the following array of integers:

int[] numbers = {4, 5, 1, 3, 7, 4, 1};

Since this is an array of primitives, the solution can simply loop the array and return to the first occurrence of the given integer, as follows:

public static boolean containsElement(int[] arr, int toContain) {  for (int elem: arr) {    if (elem == toContain) {      return true;    }  }  return false;}

Another solution to this problem can rely on the Arrays.binarySearch() methods. There are several flavors of this method, but in this case, we need this one: int binarySearch​(int[] a, int key). The method will search the given key in the given array and will return the corresponding index or a negative value. The only issue is that this method ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Java Coding Problems - Second Edition

Java Coding Problems - Second Edition

Anghel Leonard
Java in a Nutshell, 7th Edition

Java in a Nutshell, 7th Edition

Benjamin J. Evans, David Flanagan
The Well-Grounded Java Developer, Second Edition

The Well-Grounded Java Developer, Second Edition

Benjamin Evans, Martijn Verburg, Jason Clark

Publisher Resources

ISBN: 9781789801415Supplemental Content