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
Related
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.
Hey guys im new to java and i came across this thing
Ok so here i got something i just cant comprehend
here i have this class:
class FailSoftArray {
private int a[]; // reference to array
private int errval;
public int length;
public FailSoftArray(int size, int errv) {
a = new int[size];
errval = errv;
length = size;
}
public int get(int index) {
if(indexOK(index)) return a[index];
return errval;
}
public boolean put(int index, int val) {
if(indexOK(index)) {
a[index] = val;
return true;
}
return false;
}
private boolean indexOK(int index) {
if(index >= 0 & index < length) return true;
return false;
}
}
What does indexOK(index) mean? What does it do?
This is a method to determine if the index its going to get in the array is valid.
Normally, if a value less than zero or greater than or equal to the length of the array was used as an index, it would cause an error, throwing an IndexOutOfBoundsException, since an array is indexed from 0 to length - 1.
The method avoids that possible outcome by ensuring the index will always be valid before using it, and it does this by comparing the index to see if it's >= 0, then comparing < length, then the & makes sure both are true (if both conditions are true, it can be used as an index to the array without throwing an exception.)
When you call indexOK, your program runs the following method, with an index as an argument:
private boolean indexOK(int index) {
if(index >= 0 & index < length) return true;
return false;
}
}
indexOK returns a boolean value, so the result is either true or false. When is the result true?
if(index >= 0 & index < length) return true;
return false;
If the argument is larger than or equal to zero AND the argument is less than length, the result is true. Otherwise, the result is false.
The purpose of indexOK is to check whether or not a value is an appropriate index for an array. A negative index is invalid, as is an index which equals or exceeds the length of the array it references. So the check
index >= 0
determines whether or not the index is negative, and the check
index < length
determines whether or not the index equals or exceeds the length of the array it references.
Let me rewrite the method in a way that is more understandable:
private boolean indexOK(int index) {
if(index >= 0 & index < length) {
return true;
}
return false;
}
The method will return true, when the value of index is atleast 0 and smaller than length at the same time. You can use an if-statement without its curly brackets, but it will only use the following line as the 'inner block'. This is a rather bad practice, since it's a little unclear. Furthermore, it can be easily the cause of unwanted bugs and errors, since adding lines to the 'inner block' without adding curly brackets around them isn't that uncommon. In my humble opinion, 1 line (or 2 brackets) more of code isn't that much and one should always add them.
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
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;
}
I have a collection, and I want to implement the add() method, such that only positive integers can be added to the collection. The collection can hold 4 values, and I have used the code below to initialize every value as "-1".
public class Bag implements Collection {
private int[] elements;
public Bag() {
elements = new int[Runner.SIZE_OF_COLLECTION];
for (int i = 0; i < Runner.SIZE_OF_COLLECTION; i++) {
elements[i] = -1;
}
}
So far in the method add() below, I have this loop iterating through each element in the collection, and replacing each element that's less than 0 with the positive integer that I want to add ("toAdd").
The problem is, I only want to add the positive integer "toAdd" once, and without a break in the loop, the method replaces EVERY element "-1" in the collection with the positive integer. With the break in the loop, the method fails to add the positive integer at all. Any ideas on how I can get the method to add the positive integer to the collection only once?
public void add(int toAdd) {
for (int i = 0; i < Runner.SIZE_OF_COLLECTION; i++) {
if (elements[i] <= 0 && toAdd>0) {
elements[i] = toAdd;
}
break;
}
}
Thanks in advance!
Move the break into the if statement.
You could use an ArrayList instead of an int array. With an ArrayList, you could get the index of the first occurence of -1 and use the set method to add your new value at that index.
This replaces the first value from elements, which is equal or less than 0, with value from toAdd argument.
public void add(int toAdd) {
for (int i = 0; i < Runner.SIZE_OF_COLLECTION; i++) {
if (elements[i] <= 0 && toAdd>0) {
elements[i] = toAdd;
break;
}
}
}
The add method for the interface Collection takes an Object (or a generic type, which you have not specified). If you are trying to override / implement the collection interface method with your add method, then the method signature is incorrect, and it will never be called.
Your class needs to look like:
public class Bag implement Collection<Integer>
{
// ... other necessary methods
public boolean add(Integer i)
{
// your method...
}
}
And probably easier than your implementation would be to do:
public class Bag extends java.util.ArrayList<Integer>
{
#Override
public boolean add(Integer i)
{
if ((i != null) && (i > 0)) super.add(e);
}
}
You probably need to override the other add methods as well, although truthfully, it would be better to encapsulate the ArrayList instead of extending it.