How to check whether an array with a specific Index is empty? - java

I followed the points made in this thread, but I get the error "the operator is undefinded for the argument types[...]"
How can I check whether an array is null / empty?
My code:
public class Test{
private int[] array = new int [5];
public int method(int i) {
for(int s = 0; s <= array.length; s++) {
if( array[s] != null) { //I get the error in here even though the highest upvoted answer in the linked question recommends this solution. I obviously cant check it for 0, because the user input can be 0.
array[s] = i;
} else {
method(i);
}
}
}
}
Thanks!

You are getting this error as int is a primitive type. In your case array[s] returns an int not an Integer. Int can't be a null.
Change your array from int[] to Integer[] if you want to check null.
private Integer[] array = new Integer[5];

You have array of int which is primitive type, primitive types in Java can't be null so compiler gives error when checking if it is null, if you really want it you can use Integer which is wrapper class for int.

Related

What is the best way to check if ALL values in a range exist in an array? (java)

I have the task of determining whether each value from 1, 2, 3... n is in an unordered int array. I'm not sure if this is the most efficient way to go about this, but I created an int[] called range that just has all the numbers from 1-n in order at range[i] (range[0]=1, range[1]=2, ect). Then I tried to use the containsAll method to check if my array of given numbers contains all of the numbers in the range array. However, when I test this it returns false. What's wrong with my code, and what would be a more efficient way to solve this problem?
public static boolean hasRange(int [] givenNums, int[] range) {
boolean result = true;
int n = range.length;
for (int i = 1; i <= n; i++) {
if (Arrays.asList(givenNums).containsAll(Arrays.asList(range)) == false) {
result = false;
}
}
return result;
}
(I'm pretty sure I'm supposed to do this manually rather than using the containsAll method, so if anyone knows how to solve it that way it would be especially helpful!)
Here's where this method is implicated for anyone who is curious:
public static void checkMatrix(int[][] intMatrix) {
File numberFile = new File("valid3x3") ;
intMatrix= readMatrix(numberFile);
int nSquared = sideLength * sideLength;
int[] values = new int[nSquared];
int[] range = new int[nSquared];
int valCount = 0;
for (int i = 0; i<sideLength; i++) {
for (int j=0; j<sideLength; j++) {
values[valCount] = intMatrix[i][j];
valCount++;
}
}
for (int i=0; i<range.length; i++) {
range[i] = i+1;
}
Boolean valuesThere = hasRange(values, range);
valuesThere is false when printed.
First style:
if (condition == false) // Works, but at the end you have if (true == false) or such
if (!condition) // Better: not condition
// Do proper usage, if you have a parameter, do not read it in the method.
File numberFile = new File("valid3x3") ;
intMatrix = readMatrix(numberFile);
checkMatrix(intMatrix);
public static void checkMatrix(int[][] intMatrix) {
int nSquared = sideLength * sideLength;
int[] values = new int[nSquared];
Then the problem. It is laudable to see that a List or even better a Set approach is the exact abstraction level: going into detail not sensible. Here however just that is wanted.
To know whether every element in a range [1, ..., n] is present.
You could walk through the given numbers,
and for every number look whether it new in the range, mark it as no longer new,
and if n new numbers are reached: return true.
int newRangeNumbers = 0;
boolean[] foundRangeNumbers = new boolean[n]; // Automatically false
Think of better names.
You say you have a one dimensional array right?
Good. Then I think you are thinking to complicated.
I try to explain you another way to check if all numbers in an array are in number order.
For instance you have the array with following values:
int[] array = {9,4,6,7,8,1,2,3,5,8};
First of all you can order the Array simpel with
Arrays.sort(array);
After you've done this you can loop through the array and compare with the index like (in a method):
for(int i = array[0];i < array.length; i++){
if(array[i] != i) return false;
One way to solve this is to first sort the unsorted int array like you said then run a binary search to look for all values from 1...n. Sorry I'm not familiar with Java so I wrote in pseudocode. Instead of a linear search which takes O(N), binary search runs in O(logN) so is much quicker. But precondition is the array you are searching through must be sorted.
//pseudocode
int range[N] = {1...n};
cnt = 0;
while(i<-inputStream)
int unsortedArray[cnt]=i
cnt++;
sort(unsortedArray);
for(i from 0 to N-1)
{
bool res = binarySearch(unsortedArray, range[i]);
if(!res)
return false;
}
return true;
What I comprehended from your description is that the array is not necessarily sorted (in order). So, we can try using linear search method.
public static void main(String[] args){
boolean result = true;
int[] range <- Contains all the numbers
int[] givenNums <- Contains the numbers to check
for(int i=0; i<givenNums.length; i++){
if(!has(range, givenNums[i])){
result = false;
break;
}
}
System.out.println(result==false?"All elements do not exist":"All elements exist");
}
private static boolean has(int[] range, int n){
//we do linear search here
for(int i:range){
if(i == n)
return true;
}
return false;
}
This code displays whether all the elements in array givenNums exist in the array range.
Arrays.asList(givenNums).
This does not do what you think. It returns a List<int[]> with a single element, it does not box the values in givenNums to Integer and return a List<Integer>. This explains why your approach does not work.
Using Java 8 streams, assuming you don't want to permanently sort givens. Eliminate the copyOf() if you don't care:
int[] sorted = Arrays.copyOf(givens,givens.length);
Arrays.sort(sorted);
boolean result = Arrays.stream(range).allMatch(t -> Arrays.binarySearch(sorted, t) >= 0);
public static boolean hasRange(int [] givenNums, int[] range) {
Set result = new HashSet();
for (int givenNum : givenNums) {
result.add(givenNum);
}
for (int num : range) {
result.add(num);
}
return result.size() == givenNums.length;
}
The problem with your code is that the function hasRange takes two primitive int array and when you pass primitive int array to Arrays.asList it will return a List containing a single element of type int[]. In this containsAll will not check actual elements rather it will compare primitive array object references.
Solution is either you create an Integer[] and then use Arrays.asList or if that's not possible then convert the int[] to Integer[].
public static boolean hasRange(Integer[] givenNums, Integer[] range) {
return Arrays.asList(givenNums).containsAll(Arrays.asList(range));
}
Check here for sample code and output.
If you are using ApacheCommonsLang library you can directly convert int[] to Integer[].
Integer[] newRangeArray = ArrayUtils.toObject(range);
A mathematical approach: if you know the max value (or search the max value) check the sum. Because the sum for the numbers 1,2,3,...,n is always equal to n*(n+1)/2. So if the sum is equal to that expression all values are in your array and if not some values are missing. Example
public class NewClass12 {
static int [] arr = {1,5,2,3,4,7,9,8};
public static void main(String [] args){
System.out.println(containsAllValues(arr, highestValue(arr)));
}
public static boolean containsAllValues(int[] arr, int n){
int sum = 0;
for(int k = 0; k<arr.length;k++){
sum +=arr[k];
}
return (sum == n*(n+1)/2);
}
public static int highestValue(int[]arr){
int highest = arr[0];
for(int i = 0; i < arr.length; i++) {
if(highest<arr[i]) highest = arr[i];
}
return highest;
}
}
according to this your method could look like this
public static boolen hasRange (int [] arr){
int highest = arr[0];
int sum = 0;
for(int i = 0; i < arr.length; i++) {
if(highest<arr[i]) highest = arr[i];
}
for(int k = 0; k<arr.length;k++){
sum +=arr[k];
}
return (sum == highest *(highest +1)/2);
}

how to implement a void method as opposed to a method that returns something?

I am just consfused on how to implement these two methods like how call them or use them? Since the first one is void how does it work?
someone please use and an array and implement this for me or help me understand how the first void method works?
public static void insertionsort(int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
int copyNumber = numbers[i];
int j = i;
while (j > 0 && copyNumber < numbers[j-1]) {
numbers[j] = numbers[j-1];
j--;
}
numbers[j] = copyNumber;
}
}
public int[] InsertionSort(int[] data){
int len = data.length;
int key = 0;
int i = 0;
for(int j = 1;j<len;j++){
key = data[j];
i = j-1;
while(i>=0 && data[i]>key){
data[i+1] = data[i];
i = i-1;
data[i+1]=key;
}
}
return data;
}
A function with return type does something (executes code) and returns some result back to the code that called that function. A function without return type executes some code but does not return a result ( because it is not needed in most cases )
Consider this two functions:
public static int withResult( int someParameter)
{
//execute some code here
int someReturnValue = //result of the code above
return someReturnValue;
}
public static void withoutResult( int someParameter)
{
//execute some code here which produces no result which could be of interest to the caller (calling code)
} //end the function without returning anything
You would call it like this:
int result;
result = withResult( 1234 );//executes the function and stores its return type in 'result'
withResult( 468 );//executes the function but does not store the return type anywhere ("throws it away")
withoutResult ( 1234 );//simply executes the function
result = withoutResult ( 5678 ); //this makes no sense because the function does not return anything
In java everything is passed by value, including references. In your void method, the value of a reference to the array is passed. So while you cannot assign a new int [] to numbers, you are able to change the ints in numbers.
The first method, returning void (i.e., not returning anything) is passed an array as a parameter. What is passed is a reference to an array that is declared and for which memory is allocated outside the method. The method sorts that information in place; when the method returns, the data in that array is then sorted.
int[] myArray = getArrayInfo(); // assume this gets data in an array
WhateverClass.insertionSort(myArray); // this will sort that data
// at this point, myArray will be sorted

How can I set arrays in Java?

Here is my code:
int setElement(int[]array) {
int key;
for (int i=0; i<array.length; i++) {
}
return key;
}
Something is wrong here.
As you said, your method needs to take three parameters, but your method takes just one input array. Also there is no need to loop through the array, array element can be accessed using its index for insertion, also for retrieval. Since the index is passed as parameter you can use it directly in your code.
All you need to do is
public void setValueInArray(int[] array, int index, int value){
if(array != null && index >= 0 && index < array.length){
array[index] = value;
}
}
key should be passed to the method.
The way you're doing it you'll never meet the if condition since key has a garbage value - It's only declared but never defined.
Try to pass the index and the value you are trying to change.
public void setElement(int[] array, int index, int val ) {
if(array!=null && index >-1 && index<array.length ){
array[index]=val ;
} else{
//sorry not possible
}
}
Integer myArray[]= {12,23,10,22,10};
System.out.println(Arrays.asList(myArray).indexOf(23));
use above code

Finding if an array contains all elements in another array

I am trying to loop through 2 arrays, the outer array is longer then the other. It will loop through the first and if the 2nd array does not contain that int it will return a false. But I cannot figure out how to go about this. This is what I have so far:
public boolean linearIn(int[] outer, int[] inner) {
for (int i = 0; i < outer.length; i++) {
if (!inner.contains(outer[i])) {
return false;
}
}
return true;
}
I am getting this error when run:
Cannot invoke contains(int) on the array type int[]
I am wondering if it can be done without using a nested loop (like above). I know I'm doing something wrong and if anyone could help on the matter it would be great. Also I wasn't sure what class to look for in the java doc for the int[].
You could check that the larger of the arrays outer contains every element in the smaller one, i.e. inner:
public static boolean linearIn(Integer[] outer, Integer[] inner) {
return Arrays.asList(outer).containsAll(Arrays.asList(inner));
}
Note: Integer types are required for this approach to work. If primitives are used, then Arrays.asList will return a List containing a single element of type int[]. In that case, invoking containsAll will not check the actual content of the arrays but rather compare the primitive int array Object references.
You have two options using java.util.Arrays if you don't want to implement it yourself:
Arrays.toList(array).contains(x) which does exactly you are doing right now. It is the best thing to do if your array is not guaranteed to be sorted.
Arrays.binarySearch(x,array) provided if your array is sorted. It returns the index of the value you are search for, or a negative value. It will be much, much faster than regular looping.
If you would like to use contains then you need an ArrayList. See: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#contains(java.lang.Object)
Otherwise, you need two loops.
There is a workaround like this:
public boolean linearIn(int[] outer, int[] inner) {
List<Integer> innerAsList = arrayToList(inner);
for (int i = 0; i < outer.length; i++) {
if (!innerAsList.contains(outer[i])) {
return false;
}
}
return true;
}
private List<Integer> arrayToList(int[] arr) {
List<Integer> result= new ArrayList<Integer>(arr.length);
for (int i : arr) {
result.add(i);
}
return result;
}
But don't think that looping is not happening, just because you don't see it. If you check the implementation of the ArrayList you would see that there is a for loop:
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/ArrayList.java#ArrayList.indexOf(java.lang.Object)
So you are not gaining any performance. You know your model best, and you might be able to write more optimized code.
The question above is a practice in my class. There is my friend' solution:
public boolean contains(int[] arrA, int[] arrB) {
if (arrB.length > arrA.length) return false;
if (arrB.length == 0 && arrA.length == 0) return false;
for (int count = 0, i = 0; i < arrA.length; i++) {
if (arrA[i] == arrB[count]) {
count++;
} else {
count = 0;
}
if (count == arrB.length) return true;
}
return false;
}
int[] is a primitive array. Meaning it does not have any special methods attached to it. You would have to manually write your own contains method that you can pass the array and the value to.
Alternatively you could use an array wrapper class such as ArrayList which does have a .contains method.
ArrayList<Integer> inner = new ArrayList<Integer>();
boolean containsOne = inner.contains(1);
contain method is reserved for ArrayList
Try this:
public boolean linearIn(int[] outer, int[] inner) {
for (int i = 0; i < outer.length; i++) {
for (int j = 0; j < inner.length; j++) {
if (outer[i] == inner[j])
return false;
}
}
return true;
}

Java Generic Casting Type Mismatch

public class MaxHeap<T extends Comparable<T>> implements Heap<T>{
private T[] heap;
private int lastIndex;
public void main(String[] args){
int i;
T[] arr = {1,3,4,5,2}; //ERROR HERE *******
foo
}
public T[] Heapsort(T[]anArray, int n){
// build initial heap
T[]sortedArray = anArray;
for (int i = n-1; i< 0; i--){
//assert: the tree rooted at index is a semiheap
heapRebuild(anArray, i, n);
//assert: the tree rooted at index is a heap
}
//sort the heap array
int last = n-1;
//invariant: Array[0..last] is a heap,
//Array[last+1..n-1] is sorted
for (int j=1; j<n-1;j++) {
sortedArray[0]=sortedArray[last];
last--;
heapRebuild(anArray, 0, last);
}
return sortedArray;
}
protected void heapRebuild(T[ ] items, int root, int size){
foo
}
}
The error is on the line with "T[arr] = {1,3,4,5,2}"
Eclipse complains that there is a:
"Type mismatch: cannot convert from
int to T"
I've tried to casting nearly everywhere but to no avail.A simple way out would be to not use generics but instead just ints but that's sadly not an option. I've got to find a way to resolve the array of ints {1,3,4,5,2} into an array of T so that the rest of my code will work smoothly.
When you use a generic type, you must resolve all the type parameters, i.e. tell the compiler which concrete types you want to use instead of the placeholder T in your code. As the others already pointed out, a primitive type like int can't be used as a generic type parameter - it must be a reference type, like Integer. So you can rewrite your main method into something like
public static void main(String[] args){
int i = 5;
Integer[] arr = {1,3,4,5,2};
MaxHeap<Integer> maxHeap = new MaxHeap<Integer>();
maxHeap.heapSort(arr, i);
}
Note that it should be static. When you instantiate your class, you have to specify the type parameter Integer as above. Then you can pass it the array to be sorted.
A further note: this loop
for (int i = n-1; i< 0; i--){
...
}
will never execute - the loop condition should be i > 0 instead.
Declare arr as an Integer[] instead of a T[]. There are also a couple of other small errors that I fixed here:
public static void main(String[] args){
int i;
Integer[] arr = {1,3,4,5,2}; //ERROR HERE *******
}
public <T> T[] Heapsort(T[]anArray, int n){
// build initial heap
T[]sortedArray = anArray;
for (int i = n-1; i< 0; i--){
//assert: the tree rooted at index is a semiheap
heapRebuild(anArray, i, n);
//assert: the tree rooted at index is a heap
}
//sort the heap array
int last = n-1;
//invariant: Array[0..last] is a heap,
//Array[last+1..n-1] is sorted
for (int j=1; j<n-1;j++) {
sortedArray[0]=sortedArray[last];
last--;
heapRebuild(anArray, 0, last);
}
return sortedArray;
}
protected void heapRebuild(T[ ] items, int root, int size){
//foo
}
You've already said that T extends Comparable<T>. "int" does not extend Comparable<T> not matter how you cast it.
Erm, ever thought about what would happen if you ran this code in a MaxHeap of, say, String objects?
T does not exist until you actually instantiate the generic class. So, it does not make sense to create an array of T with integers if you don't know what T is.
EDIT: Also, generics in Java only work with reference types, and int is a value type. Try using Integer (int's wrapper class) instead.

Categories

Resources