Returning an Array of Integers - java

I am trying to make a method in which it will take an array of integers as a parameter, creates a new array that is the same size, copies the elements from the first array into the new array, and then returns a reference to the new array.
Right now, my code is as follows:
class CopyingAnArray {
int[] cloneArray(int[] arr) {
size = newarray.length;
int[] newarray = new int[size];
int[] copyarray = newarray;
return copyarray;
}
public static void main(String argv[]) {
ArrayTester converter = new ArrayTester();
int[] newarray = {2,5,6,7};
System.out.println(converter.cloneArray(newarray));
}
}
Here is an explanation of what I think I am doing. I am taking the size of an array and putting it an array:
size = newarray.length;
int[] newarray = new int[size];
Then I am copying the array into a new array named copyarray. Then, I return copyarray.
int[] newarray = new int[size];
int[] copyarray = newarray;
return copyarray;
Any suggestions or advice on what I did wrong/solve the code?
so I tried doing this instead:
So, I will do something like this:
int[] cloneArray(int[] arr) {
int size=arr.length;
int[] arr=new int[size];
int[] arr=newarray;
for (int i=0; i<arr.length; i++) {
arr[i]=newarray[i];
return newarray[i];
}
}
I am still getting errors though.

Multiple things. You need to declare size as an int. The major things: you never use the parameter passed to the method, arr. You use size = newarray.length when newarray doesn't exist yet. You try to make copyarray = new array, which doesn't make much sense. In addition, when setting two arrays equal to each other, you aren't really copying, you are only copying the reference to the array in memory. In order to copy, make a new array with the length of the parameter, then iterate over it with a for loop and copy each value into the new array, then return the new array. You can also always use Arrays.copyOf(array,array.length);

Related

How would I add, delete or insert arrays in Java using static methods (no ArrayLists)

I am trying to self-learn Java, and have an issue with these arrays I have to make without ArrayLists. I tried to look online on static methods, but I can't find anything that could help me understand. I have to make 3 methods that can be used to modify arrays. So, for adding a value to the end of an array, the method should have the array and the value as parameters. It should then return a new array which is the same as the old array but with the added on value. The site I'm trying to learn this on shows me the block of code and explains what methods do, but it doesn't show me how to use them.
public class Arrays {
static void array() {
System.out.print("1, 2, 4, 7");
}
static void add() {
System.out.print(", 11");
}
public static void main(String[] args) {
System.out.println("Array:");
array();
System.out.println(" ");
System.out.println("Array with Added End:");
array();
add();
System.out.println(" ");
}
}
...for adding a value to the end of an array, the method should have the array and the value as parameters. It should then return a new array which is the same as the old array but with the added on value.
I'm going to assume that add is the method that will add something to your array and that your array is of type int[]. I'll build the method step-by-step:
method should have the array and the value as parameters
add(int[] arr, int val) {}
It should then return a new array which is the same as the old array
The return type of the method must therefore be the same as the array parameter arr. Since you stated the method must be static:
public static int[] add(int[] arr, int val)
{
// todo: make this work
}
It should then return a new array which is the same as the old array but with the added on value.
Arrays cannot be resized so you need to create a new array (which is also specified in the instructions) that is large enough to hold all the elements of arr plus one additional element. There are several ways to populate your new array:
Copying each element yourself:
public static int[] add(int[] arr, int val)
{
int[] newArray = new int[arr.length + 1];
for (int index = 0; index < arr.length; index++)
{
newArray[index] = arr[index];
}
// Arrays start at index 0 so arr.length will be the last
// position in newArray.
newArray[arr.length] = val;
return newArray;
}
Using java.util.Arrays:
public static int[] add(int[] arr, int val)
{
int[] newArray = Arrays.copyOf(arr, arr.length + 1);
newArray[arr.length] = val;
return newArray;
}
Using System.arraycopy:
public static int[] add(int[] arr, int val)
{
int[] newArray = new int[arr.length + 1];
System.arraycopy(arr, 0, newArray, 0, arr.length);
newArray[arr.length] = val;
return newArray;
}
This should be enough of an example on working with arrays to help you write the other two methods.

I read that when you declare two vectors the statement b=a doesn't have the effect we want. But I write a mini program and it works

I declare two vectors
int a[] = {1,2,3,4};
int b[] = new int[4];
And I read that if you want to copy the elements from a to b the statement b=a doesn't do that. But when I compile the code below it does copy the elements from a to b and outputs 1,2,3,4.
public static void main(String args[]) {
int a[] = {1,2,3,4};
int b[]=new int[4];
b=a;
for(int i=0; i< b.length; i++){
System.out.println(b[i]);
}
}
An array is simply a list of references to certain objects. So in the following code:
int[] a = {1,2,3,4};
int[] b = a;
The references to each int value are copied. If that reference happens to be an instance of a class and a variable whithin that class would change, it would change in both arrays.
In order to create a completely seperate array use the following:
int[] a = {1,2,3,4};
int[] b = a.clone();

How to remove and add element from java array

I have a java array. I want to remove first d items from array and store it to some other array. I am able to store but not able to remove. My Code
private static void itemRemove(int[] inputArr, int d) {
int newArr [] = new int[d];
for(int i=0;i<d;i++){
newArr[i] = inputArr[i];
}
itemPrint(inputArr);
itemPrint(newArr);
}
So in example suppose I have array
inputArr is [1,2,3,4,5] and my d is 2
I am able to add in to newArray [1,2] but not able to remove from inputArr.
Also once I remove two element from inputArr which is having size 5 so I can add two more element. Can anybody give some idea how to add element.
You need to create a new int[]array of size inputArr.length - d and copy the values:
private static int[] itemRemove(int[] inputArr, int d) {
int[] newArrd = new int[d];
int[] newArr = new int[inputArr.length-d];
int newArrIdx = 0;
for(int i=0;i<inputArr.length;i++){
if(i<d){
newArrd[i] = inputArr[i];
}else{
newArr[newArrIdx++] = inputArr[i];
}
}
return newArr;
}
You can do it using System.arrayCopy and Arrays.fill functions
int[] inputArr = {1,2,3,4,5};
int n = 3; //number of positions to move
int[] newArray = new int[n];//creating new array of size n
System.arraycopy(inputArr, 0, newArray, 0, n);//copying elements up to nth position to new array
System.arraycopy(inputArr, n, inputArr, 0, inputArr.length-n);//copying remaining elements to start position
Arrays.fill(inputArr, inputArr.length-n, inputArr.length, 0);//filling cells after the last element with default 0 value
itemPrint(newArray);
itemPrint(inputArr);
To remove element from Array you need to remove the existing index of that element as well.
As array in java is immutable so you need to re-assign the array values to new array as you are doing already with newArr[index]
Just to remove array elements without altering index you may use the predefined library of commons.apache.org like this:
array = ArrayUtils.removeElement(array, element)
Apache Common
Or, you may use the arraylist instead of this for dynamic sizing of the array.You can initialize your input array like this:
ArrayList<> inputArr= new ArrayList<>();
To remove element from inputArr with index position just use the remove(int index) method of list.
inputArr.remove(your index here);
You're not doing any removal here:
for(int i=0;i<d;i++){
newArr[i] = inputArr[i];
}
You just copy the the value from the input array to the new array. The input array is unchanged.
Arrays in Java are of a fixed size so there is no way to remove elements. The typical way you can approximate this is to replace the element with some marker (or 'sentinel') value. For objects, this could be null. For primitive values, such as integers, you might just need to choose a value arbitrarily:
for(int i = 0; i < d; i++) {
newArr[i] = inputArr[i];
inputArr[i] = -999; //marked for removal
}
This is obviously not a very good solution. What if -999 is already in the array?
The correct way to deal with this is to use a List. Lists are not fixed-size, so it is possible to remove elements. There are multiple implementations you can use. ArrayList is the closest to an array.
Your function, changed to use an ArrayList, might look like this:
private static void itemRemove(List<Integer> inputArr, int d) {
List<Integer> newArr = new ArrayList<>();
int removed = 0;
while (removed < d)
{
newArr.add(inputArr.remove(0));
removed++;
}
itemPrint(inputArr);
itemPrint(newArr);
}
There's a few different things going on here. Most notably, we had an int[] and now we have a List<Integer>. We're using what's called "generics" and generics don't work with primitive types, so we need to use what's called the "boxed type".
The other noticeable change is that the loop is different. There are difficulties removing from collections while you are iterating over them and I structured the loop differently to avoid this problem.
You can do something like this:
public class Test {
public static void main(String[] args) {
int[] array = {1,2,3,4,5,6};
System.out.println("Original Array");
itemPrint(array);
itemRemove(array, 2);
array = itemsLeft(array,2);
System.out.println("Original Array After Removing Items");
itemPrint(array);
}
private static void itemRemove(int[] inputArr, int d) {
int newArr [] = new int[d];
for(int i=0;i<d;i++) newArr[i] = inputArr[i];
System.out.println("New Array");
itemPrint(newArr);
}
private static void itemPrint(int[] array) {
for(Integer i : array) System.out.println(i);
}
private static int[] itemsLeft(int[] inputArr, int d) {
int [] itemsLeftArr = new int[inputArr.length-d];
for(int i=d, j=0; i<inputArr.length; i++, j++) {
itemsLeftArr[j] = inputArr[i];
}
return itemsLeftArr;
}
}
Output:
Original Array
1
2
3
4
5
6
New Array
1
2
Original Array After Removing Items
3
4
5
6
Elements cannot be removed from arrays. The only thing you can do is copy other elements to overwrite them. So, if your array looks like this:
1 2 3 4 5
You can copy 3, 4 and 5 down to overwrite 1 and 2, so you will be left with this:
3 4 5 4 5
(note how 4 and 5 are still there)
And then you can overwrite the last two elements with the new elements that you want to store in the array, which will leave you with this:
3 4 5 6 7
To copy elements, you can do it manually with a for loop, or you can use System.arrayCopy().

Declaration of Array not accepted

I am creating a class that will play the role of a computer player in a virtual game of sticks. However, when I use the constructor method for this class, I lose the array that I have created, even though I had already declared the array in the state attributes. After 20 minutes, I am completely lost.
I am new to Java, and am trying to learn and get better. Any help would really be appreciated.
Below is the redesigned AI class along with the error that Eclipse keeps on submitting.
public class RedesignedAI {
private int[][] largeArray;
private int AIChoiceStick;
private Random random = new Random();
private int CurrentScore[] = new int[51]; //at max, if 100 sticks are initially chosen, then each player takes at max 50 sticks,
private int h = 0; //^so why not have one more in case
public RedesignedAI(int NumberSticks) //this is a constructor method and creates the arrays that contains a
{
largeArray[][] = new int[NumberSticks][3];
int i = 0;
while(i < NumberSticks)
{
largeArray[i][0] = 1; //ADD THIS
largeArray[i][1] = 1;
largeArray[i][2] = 1;
i++;
}
}
The error: largeArray cannot be resolved to a type.
You initialized the largeArraythe wrong way. Use:
largeArray = new int[NumberSticks][3];
That new allocate a 2D array, so types are coherent both sides of the =.
If you want to allocate chunk by chunk then you should use [] syntax:
largeArray = new int[NumberSticks][]; // array of NumberSticks entries to array of int (not yet determined)
for (int i=0; i<NumberSticks; i++) {
largeArray[i] = new int[3]; // i-th entry of array largeArray is a new array of 3 ints
}
largeArray is a reference to array of reference to array of ints. largeArray[i] is a reference to array of ints. largeArray[i][j]is an int.
Try this
private int[][] largeArray = null;
Initially initialize with null.
then in constructor
largeArray[][] = new int[3][3];
Since value is dynamic and you are changing it anyhow
You have to initialize the array on the top:
private int[][] largeArray = new int[x][y];
An array always has a fixed length. Only a list can variate the length.
Change this:
largeArray[][] = new int[NumberSticks][3];
into this:
largeArray = new int[NumberSticks][3];
Wrong Code:
largeArray[][] = new int[NumberSticks][3];
Instead use:
largeArray = new int[NumberSticks][3];
You don't need the [][] in the largeArray code of the constructor. This will do:
largeArray = new int[NumberSticks][3];
You may find it easier to use ArrayList instead. Maybe something like this:
private List<List<Integer>> largeArray;
...
public RedesignedAI(int NumberSticks) {
largeArray = new ArrayList<>();
int i = 0;
while(i < NumberSticks) {
List<Integer> innerArray = new ArrayList<>();
innerArray.add(1);
innerArray.add(1);
innerArray.add(1);
largeArray.add(innerArray);
i++;
}
}

Method in java to take array as parameter, copy first elements and then double the length?

I essentially want a method that takes in my declared array and then copies the elements into a new array and then doubles the size with the remaining elements as 0. How can I make this possible? I am confused on the doubling of the array, I realize I can equal the array to the previous array to copy the elements.
class Untitled
{
public static void main(String[] args)
{
int[] a = {6, 3, 5, 2};
}
public static int[] doubleSize(int[] j)
{
int[] new = int [] j + int[] j
return int[] j;
}
}
Java automatically initialized the elements in an integer array as 0, so you don't have to do that manually.
public static int[] doubleSize(int[] j)
{
int[] newArray = new int[j.length * 2]
for (int i = 0; i < j.length; i++) {
newArray[i] = j[i];
}
return newArray;
}
Edit: A more Java-esque solution is
public static int[] doubleSize(int[] j)
{
return Arrays.copyOf(j, 2 * j.length);
}
This is pretty simple. To create a new array with twice the length you can do:
int[] newArray = new int[j.length * 2];
Since the array is type int, each element will be initialized to 0.
So once you copy the elements from the old array you should be done.
Also, you will want to change your return statement to just
return newArray;
Hi you achieve required functionality in this way.
public class DoubleArray
{
public static void main( String[] args )
{
int a[]={2,3,4,5};
int b[]=new int[2*a.length];
b =Arrays.copyOf(a, b.length);
System.out.println("DoubleArray.main()"+b);
for(int i=0;i<b.length;i++)
{
System.out.println(b[i]);
}
}
}

Categories