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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments