Correctly input int[] in java method? - java

This method insert takes as input int[] array, int element, and int index, which inserts element into the index position of array. Since an array is not resizable, the method shifts every element over to the right of the array by one. The element at the end is removed from the array. The method returns void.
public class ShiftElements {
public static void insert(int[] array, int element, int index)
{
for (int i = array.length-1; i > index; i--)
{
array[i] = array[i-1];
}
array[index] = element;
}
}
To test if this method works, I changed the return type to int[] and wrote a main method to print array:
public class ShiftElements {
public static int[] insert(int[] array, int element, int index)
{
for (int i = array.length-1; i > index; i--)
{
array[i] = array[i-1];
}
return array;
}
public static void main(String[] args) {
System.out.print(insert(4,5,3));
}
}
I am having problems, getting this print statement to work. It's probably something simple, but I've been up for two days studying for finals so I'm pretty braindead.
I'm pretty sure I called the insert method just fine, but I think my issue is that I'm not properly inputting the type int[]. I'm not sure how I'm supposed to do this.

1) The first parameter of insert is an array of int, not an int. You must call :
insert(new int[]{4},5,3)
2) you can't print an array : so use :
println(Arrays.toString(insert(...)))

I guess what you are looking for is :
int[] i = new int[5];
System.out.print(java.util.Arrays.toString(insert(i,5,3)));
Apart from the use of java.util.Arrays.toString method Watch out the parameters that you are passing in insert method:
first parameter should be an array of int. But you are passing an int.

System.out.print(insert(4,5,3));
That statement does not pass a array of integers, you only passed and integer 4. You would need to pass, as your function is defined, int[], int, int.
System.out.print(insert(new int[4],5,3));

You made a call to insert(int,int,int) eventhough your signature for insert is insert(int[],int,int). For instance, calling insert with an array literal would be like so:
insert(new int[]{1,2,4,5}, 3, 2);
Additionally, System.arraycopy is a much faster and elegant way to copy arrays. You also seem to have forgotten to set the element at its index within your second example:
public static int[] insert(int[] array, int element, int index)
{
// Use arraycopy to shift all the elements by one, running over the last index
System.arraycopy(array, index, array, index+1, array.length-index-1);
// Set the appropriate index in the array to the specified value
array[index]=element;
return array;
}
If you then run the following, you will get your expected output:
int[] array = {1, 2, 4, 5};
insert(array,3,2); // array is now {1,2,3,4}
System.out.println(java.util.Arrays.toString(array));

If you are looking to print the array then the most laymen procedure is to return the particular array and loop throw it to print its element. eg:
public static void main(String[] args) {
int []solution= insert(new int[4],5,3);
for(int i=0;i<solution.length;i++)
{
System.out.println(solution[i]);
}
}

Related

How do use the same array of 10000 integers for two different programs?

For my program I have to compare the runtimes of sorting an array using bubble sort. The other uses parallel processing with bubble sort. The same array of 10000 integers(random integers) must be used. My program keeps creating a new array.
I tried creating an array class with an static array and a static variable called k. I have it so that when each program makes an array object, it calls an static instance method to populate the array. The method has a for-loop nested within an if-statement. After first calling the method, the variable k increments. Once the method is called once more, the if statement checks if the method was called before. If yes, the for-loop to repopulate the array is skipped and the program simply return the array with the variables it is already populated with.
public class Array
{
static int i;
static int[] array = new int[10000];
static int k;
Array()
{
populate();
}
public static int[] populate()
{
if(k==0)
{
for(i = 0; i < array.length; i++)
{
array[i] = (int)(Math.random() * 10000);
}
}
return array;
}
}
I am supposed to be getting the same array with every run. PLEASE HELP!

Is there a way to check if an array is using a default or assigned value?

I'm new to java and I'm wanting to create an array and change specific values in the array. I know that if I initialize an array like so:
int[] myArray = new int[4];
all values in the array will be set to 0. If I want to check to see if the 0 value was intentionally is there anything, such as a reference, that will be different than the default value that would indicate that the value of 0 was not set by default?
I suggest you to use an array of Integer instead of int. Then you can distinguish unassigned values by comparing an item to null because the items are initialized by null instead of zero.
Immediately fill the array with some value that is never possible to be set intentionally. For instance, if you know that legitimate values are between 0 and 40, you could do:
int[] myArray = new int[4];
Arrays.fill(myArray, 42);
Then later on you can tell if an element has been set by testing if it's 42.
You can try to set the default value to other than 0 by using looping
for( int i=0;i<myArray.length;i++){
myArray[i]=1;
}
You can create your own wrapper class around the array. This allows you to create another internal boolean array to keep track what value was modified:
public class Array {
private final int[] values;
private final boolean[] modified;
public Array(int length) {
values = new int[length];
modified = new boolean[length];
}
public void set(int index, int value) {
values[index] = value;
modified[index] = true;
}
public int get(int index) {
return values[index];
}
public boolean isDefaultValue(int index) {
return !modified[index];
}
}

Java ArrayList get() as Integer rather than Object

new to Java. Trying to understand the point of declaring my ArrayList as an <Integer>. I still have to cast my .get() result as an int in my methods for it to work, else it still returns an Object. eg: (int) deliv.get(j) int the Sort method's for loop. Is there a way to avoid this or is my code the correct approach?
Problem: Assume the array can change size, hence not just using primitive array. All numbers should be pairs, looking for the unique one missing it's pair value. I sort the array, then cycle through the pairs to look for a mismatch. Thanks.
import java.util.*;
class StolenDrone{
public static void main(String[] args){
ArrayList<Integer> deliv_id = new ArrayList<>();
deliv_id.add(99);
deliv_id.add(13);
deliv_id.add(4);
deliv_id.add(5);
deliv_id.add(8);
deliv_id.add(99);
deliv_id.add(8);
deliv_id.add(5);
deliv_id.add(4);
System.out.println("Array is: " + deliv_id);
sort(deliv_id);
System.out.println("Array is: " + deliv_id);
int unique = findUnique(deliv_id);
System.out.println("Unique ID is: " + unique);
}
//Sort ArrayList into increasing order
static void sort(ArrayList deliv){
int temp;
for(int i = 0; i<deliv.size();i++){
for (int j=0; j<deliv.size()-1;j++){
if((int) deliv.get(j)> (int) deliv.get(j+1)){
temp = (int) deliv.get(j+1);
deliv.set(j+1, deliv.get(j));
deliv.set(j, temp);
}
}
}
}
//check pairs in ArrayList to find unique entry
static int findUnique(ArrayList deliv){
for(int i = 0; i<deliv.size()-1;i+=2){
if(deliv.get(i) == null){
return -1; //no unique
}
if((int) deliv.get(i) != (int) deliv.get(i+1)){
return (int) deliv.get(i);
}
}
return -1;
}
}
When you type parameterize ArrayList<Integer> the compiler knows that everything inside the ArrayList is of type Integer and will only allow you to add Integers to the list, and thus get() returns Integer. Without parameterizing the compiler will allow you to add any Object to the ArrayList, and thus calling get() will return an Object and requiring the cast to int.
To remove the need for casts you need to change parameters with type ArrayList to ArrayList<Integer> in the function declaration.
static void sort(ArrayList deliv)
Your method signature requests an untyped ArrayList.
The compiler cannot know what will be inside the ArrayList so it requires you to cast the result.
Change it to this:
static void sort(ArrayList<Integer> deliv)
Now the compiler knows it is an ArrayList of Integers.
So you wont need to add the cast to get()
In Java Integet is wrapper-class of int. You cannot set int as a type of ArrayList to work, but you can put there int type and it will be automatticly casted to Integer. To meke work it good you should do like this :
static void sort(ArrayList deliv){
int temp;
for(int i = 0; i<deliv.size();i++){
for (int j=0; j<deliv.size()-1;j++){
if(deliv.get(j)> deliv.get(j+1)){ // You should not cast, Integer is Comparable
temp = deliv.get(j+1).intValue();//Changes here
deliv.set(j+1, deliv.get(j).intValue());//And here
deliv.set(j, temp);
}
}
}
}
Good luck

Array Funkiness in Java when passed to function

When I pass an array as function parameter in Java, say:
public static void main(String... args){
int[] in=new int[]{57,40...23};
int[] post=new int[]{50,18...0};//arrays abbreviated for expediency
treeNode tree=buildTree(in, post);
print(tree);
}
public static treeNode buildTree(int[] in, int[] post)
{
int root_data= post[(post.length)-1];
int root_index=search(root_data, in);
treeNode root=new treeNode(root_data);
root.setLeft(buildTree(subArray(in, 0, root_index),subArray(post, 0, root_index)));
root.setRight(buildTree(subArray(in,root_index+1, in.length),
subArray(post,root_index, post.length-1)));
return root;
}
public static int[] subArray(int[] array, int start, int end)
{
int[] result=new int[end-start];
for(int i=0; i<end-start;i++)
{
result[i]=array[start+i];
}
return result;
}
public static int search(int key, int[] array)
{
for(int i=0; i<array.length; i++){
if(array[i]==key)
return key;
}
return array.length;
}
I get an arrayIndexOutOfBounds exception. Through the debugger I discovered that mysteriously the arrays became length 0. Why is this?
In your search() method you probably want to return i instead of key. Since you later use root_index variable (that you found with this function) as array index, that's where you might have troubles (arrayIndexOutOfBounds exception thrown). Even if root_index is within the range of array indices, its value is still wrong - to be exact, it's 0 in your example, and subArray() method returns empty array.
You might want to consider using standard tools instead of your own methods:
Arrays.sort() followed by Arrays.binarySearch() to search: even though asymptotically it's worse than your simple search - O(n*lon(n)) to sort plus O(log(n)) to binary search vs. O(n) in your case - considering you probably have small arrays this is still reasonable, but you get the guaranteed correctness of the algorithm
Arrays.copyOfRange() to copy range of array
Also, I don't see any definition of the treeNode class, but I guess you just omitted it in your posted code piece for the sake brevity.
A quick note on the style too: in Java, variables and methods are called using camelCase (so you might want to rename root_index into rootIndex and so on) and classes begin with the upper-case letter (so treeNode would better be named TreeNode). It will make your code more (intuitively) understandable to other people when they read it.
Hope that helps!

Modify an array passed as a method-parameter

Suppose I have an int-array and I want to modify it. I know that I cannot assign a new array to array passed as parameter:
public static void main(String[] args)
{
int[] temp_array = {1};
method(temp_array);
System.out.println(temp_array[0]); // prints 1
}
public static void method(int[] n)
{
n = new int[]{2};
}
while I can modify it:
public static void main(String[] args)
{
int[] temp_array = {1};
method(temp_array);
System.out.println(temp_array[0]); // prints 2
}
public static void method(int[] n)
{
n[0] = 2;
}
Then, I tried to assign an arbitrary array to the array passed as parameter using clone():
public static void main(String[] args)
{
int[] temp_array = {1};
method(temp_array);
System.out.println(temp_array[0]); // prints 1 ?!
}
public static void method(int[] n)
{
int[] temp = new int[]{2};
n = temp.clone();
}
Now, I wonder why it prints 1 in last example while I'm just copying the array with clone() which it's just copying the value not the reference. Could you please explain that for me?
EDIT: Is there a way to copy an array to object without changing the reference? I mean to make last example printing 2.
Your examples 1 and 3 are virtually the same in context of the question - you are trying to assign a new value to n (which is a reference to an array passed by value).
The fact that you cloned temp array doesn't matter - all it did was create a copy of temp and then assign it to n.
In order to copy values into array passed into your method method you might want to look at:System.arraycopy
It all, of course, depends on the sizes of your n array and the one you create inside method method.
Assuming they both have the same length, for example, you would do it like that:
public static void main(String[] args)
{
int[] temp_array = {1};
method(temp_array);
System.out.println(temp_array[0]);
}
public static void method(int[] n)
{
int[] temp = new int[]{2};
System.arraycopy(temp, 0, n, 0, n.length);
// or System.arraycopy(temp, 0, n, 0, temp.length) -
// since we assumed that n and temp are of the same length
}
In your method
public static void method(int[] n)
n is another name for the array that way passed in. It points to the same place in memory as the original, which is an array of ints. If you change one of the values stored in that array, all names that point to it will see the change.
However, in the actual method
public static void method(int[] n) {
int[] temp = new int[]{2};
n = temp.clone();
}
You're creating a new array and then saying "the name 'n' now points at this, other array, not the one that was passed in". In effect, the name 'n' is no longer a name for the array that was passed in.
As you correctly note, you cannot assign to the array reference passed as a parameter. (Or more precisely, the assignment won't have any effect in the caller.)
This is about the best that you can do:
public static void method(int[] n) {
int[] temp = new int[]{2};
for (int i = 0; i < temp.length; i++) {
n[i] = temp[i];
}
// ... or the equivalent using System.arraycopy(...) or some such
}
Of course, this only works properly if the size of the input array is the same as the size of the array you are copying to it. (How you should deal with this will be application specific ...)
For the record Java passes the array reference by value. It doesn't pass the array contents by value. And clone won't help to solve this problem. (At least, not with the method signature as declared.)
In your method method, nothing that you assign to n will ever change the value of the object passed in and assigned to n. At the beginning of method, n points to an array. When you assign n to equal another array, you've simply re-pointed which array n points to, and haven't changed anything about temp_array from the main method.

Categories