filling values in array - java

what i want to do is fill the empty aray kyo[] with the add() method but it keeps getting an error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
0 at TestPlass.Add(TestPlass.java:30) at
TestPlass.main(TestPlass.java:18)
i'm just new to programming
public static int size = 30;
public static void main (String args[]) {
int kyo[] = {};
Add(kyo);
for(int x:kyo){
System.out.print(x + " ");
}
}
static void Add(int x[]){
for(int g=0; g<=size; g++){
x[g] = g;
}
}

If your kyo array has a fized size, you need to create it with this size.
public static int size = 30;
public static void main(String args[]) {
int kyo[] = new int[size];
add(kyo);
for (int x : kyo) {
System.out.print(x + " ");
}
}
static void add(int x[]) {
for (int g = 0; g < x.length; g++) {
x[g] = g;
}
}
You add function receives int x[] as input, so it should use x.length for the iterator and not your size variable.
I have also edited the name of your Add() method to be add() to respect Java code conventions.

An empty array can never have any content.
Once an array has been created, its size is fixed - you can change the content of the elements, but you can't change how many elements it has. See the Java arrays tutorial for more information.
If you need a dynamically-sized collection, I suggest you use a List<E> implementation, such as ArrayList<E>:
List<Integer> list = new ArrayList<>();
add(list);
for (int x : list) {
System.out.print(x + " ");
}
...
private static void add(List<Integer> list) {
// I assume you want "size" elements, not "size + 1"
for (int g = 0; g < size; g++) {
list.add(g);
}
}

This line:
int kyo[] = {};
creates an array of size zero. Arrays have a fixed size in Java; once an array has been created, its size is fixed. You have to create the array like this:
int[] kyo = new int[30];
This will create an array with 30 elements.

You need to give the size of the array when you create it, like:
int kyo[] = new int[size];
You can find some great info on arrays here:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Arrays do not resize themselves automatically, so the size you initialize it with will be its size forever.
Cheers,
Marcus

Your problem lies here: int kyo[] = {};
{} Creates an array of zero size. Since you are adding 31 elements to the array you need to initialize you array to appropriate size.
For example: int[] kyo = new int[31];

Related

Initialize 2d list in Java

I am new to Java and trying to create a 2d list the size of which isn't fixed.I have a class which looks like this:
public class q1 {
List<List<Integer> > L = new ArrayList<List<Integer> >();
public void set(int m,int n){
//This is the function which would get the size of the 2d list
}
}
I saw the answers but they had to be of fixed sizes, eg:
ArrayList<String>[][] list = new ArrayList[10][10];
But, I want different sizes of the list L for different objects. There were other options like copyOf, but can the above functionality be achieved just by this array?
You are mixing two things in your question, ArrayLists and arrays. ArrayList is a variable size container backed by an array. ArrayList has a constructor where you can specify the initial capacity you need so with ArrayLists it will look like:
public class q1 {
List<List<Integer>> L;
public void set(int m, int n){
L = new ArrayList<>(m); // assuming m is the number or rows
for(int i = 0; i < m; ++i) {
L.add(new ArrayList<>(n));
}
// now you have a List of m lists where each inner list has n items
}
}
With arrays, the syntax is slightly different:
public class q1 {
Integer[][] L;
public void set(int m, int n){
L = new Integer[m][]; // assuming m is the number or rows
for(int i = 0; i < m; ++i) {
L[i] = new Integer[n];
}
// now you have a array of m arrays where each inner array has n items
}
}
Moreover if all the inner arrays will have the same length (n) the set method could be simplified to:
public void set(int m, int n){
L = new Integer[m][n]; // assuming m is the number or rows
// now you have a array of m arrays where each inner array has n items
}
There's no such special syntax for Lists, but you could always just iterate over the number of smaller lists and initialize them individually. Note that passing the size to the ArrayList's constructor doesn't really set its size, but it is does allocate the space, and may save you rellocations in the future:
public void set(int m,int n){
l = new ArrayList<>(m);
for (int i = 0; i < m; ++i) {
l.add(new ArrayList<>(n));
}
}

ArrayList giving problems in java. positive integers solution to x+y+z+w = 13

So i am creating a method that basically gives all possible positive integer solutions to the problem x+y+z+w = 13. Really I have designed a program that can get all possible positive integer solutions to any number using any number of variables. I have managed to obtain the solution using this method:
public class Choose {
public static ArrayList<int[]> values;
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] loops = new int[3];
int q = 0;
values = new ArrayList<int[]>();
int[] array = new int[4];
System.out.println(choose(12,3));
NestedLoops(3,10,0,loops,13,array, 0);
for(int i = 0; i < values.size(); i++){
printArray(values.get(i));
}
}
public static void NestedLoops(int n, int k, int j,
int[] loops, int q, int[] array, int g){
if(j==n){
for(int i = 0; i< n; i++){
q-=loops[i];
}
if(q>0){
for(int i = 0; i < n; i++){
array[i] = loops[i];
}
array[n] = q;
values.add(array);
}
return;
}
for(int count = 1; count <= k; count++){
loops[j] = count;
NestedLoops(n,k,j+1,loops, 13, array, g);
}
}
}
My problem is that when i go to print the ArrayList, all i get is the last value repeated again and again. When i try to just print out the values instead of storing them in the ArrayList it works totally fine. This makes me think that the problem is with the values.add(array); line but i don't know how to fix it or what i am doing wrong. Thanks for any help offered.
Try using:
values.add(array.clone());
Every add of the same array just points to that array object. As you keep changing the same object, the final state is what is being shown for all stored elements. The print works as it just dumps the state of the array at that particular instant.

Is it possible to cut down or add up an initialized array? [duplicate]

I have searched for a way to resize an array in Java, but I could not find ways of resizing the array while keeping the current elements.
I found for example code like int[] newImage = new int[newWidth];, but this deletes the elements stored before.
My code would basically do this: whenever a new element is added, the array largens by 1. I think this could be done with dynamic programming, but I'm, not sure how to implement it.
You can't resize an array in Java. You'd need to either:
Create a new array of the desired size, and copy the contents from the original array to the new array, using java.lang.System.arraycopy(...);
Use the java.util.ArrayList<T> class, which does this for you when you need to make the array bigger. It nicely encapsulates what you describe in your question.
Use java.util.Arrays.copyOf(...) methods which returns a bigger array, with the contents of the original array.
Not nice, but works:
int[] a = {1, 2, 3};
// make a one bigger
a = Arrays.copyOf(a, a.length + 1);
for (int i : a)
System.out.println(i);
as stated before, go with ArrayList
Here are a couple of ways to do it.
Method 1: System.arraycopy():
Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array. A subsequence of array components are copied from the source array referenced by src to the destination array referenced by dest. The number of components copied is equal to the length argument. The components at positions srcPos through srcPos+length-1 in the source array are copied into positions destPos through destPos+length-1, respectively, of the destination array.
Object[] originalArray = new Object[5];
Object[] largerArray = new Object[10];
System.arraycopy(originalArray, 0, largerArray, 0, originalArray.length);
Method 2: Arrays.copyOf():
Copies the specified array, truncating or padding with nulls (if necessary) so the copy has the specified length. For all indices that are valid in both the original array and the copy, the two arrays will contain identical values. For any indices that are valid in the copy but not the original, the copy will contain null. Such indices will exist if and only if the specified length is greater than that of the original array. The resulting array is of exactly the same class as the original array.
Object[] originalArray = new Object[5];
Object[] largerArray = Arrays.copyOf(originalArray, 10);
Note that this method usually uses System.arraycopy() behind the scenes.
Method 3: ArrayList:
Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector, except that it is unsynchronized.)
ArrayList functions similarly to an array, except it automatically expands when you add more elements than it can contain. It's backed by an array, and uses Arrays.copyOf.
ArrayList<Object> list = new ArrayList<>();
// This will add the element, resizing the ArrayList if necessary.
list.add(new Object());
You could just use ArrayList which does the job for you.
It is not possible to change the Array Size.
But you can copy the element of one array into another array by creating an Array of bigger size.
It is recommended to create Array of double size if Array is full and Reduce Array to halve if Array is one-half full
public class ResizingArrayStack1 {
private String[] s;
private int size = 0;
private int index = 0;
public void ResizingArrayStack1(int size) {
this.size = size;
s = new String[size];
}
public void push(String element) {
if (index == s.length) {
resize(2 * s.length);
}
s[index] = element;
index++;
}
private void resize(int capacity) {
String[] copy = new String[capacity];
for (int i = 0; i < s.length; i++) {
copy[i] = s[i];
s = copy;
}
}
public static void main(String[] args) {
ResizingArrayStack1 rs = new ResizingArrayStack1();
rs.push("a");
rs.push("b");
rs.push("c");
rs.push("d");
}
}
You could use a ArrayList instead of array. So that you can add n number of elements
List<Integer> myVar = new ArrayList<Integer>();
Standard class java.util.ArrayList is resizable array, growing when new elements added.
You can't resize an array, but you can redefine it keeping old values or use a java.util.List
Here follows two solutions but catch the performance differences running the code below
Java Lists are 450 times faster but 20 times heavier in memory!
testAddByteToArray1 nanoAvg:970355051 memAvg:100000
testAddByteToList1 nanoAvg:1923106 memAvg:2026856
testAddByteToArray1 nanoAvg:919582271 memAvg:100000
testAddByteToList1 nanoAvg:1922660 memAvg:2026856
testAddByteToArray1 nanoAvg:917727475 memAvg:100000
testAddByteToList1 nanoAvg:1904896 memAvg:2026856
testAddByteToArray1 nanoAvg:918483397 memAvg:100000
testAddByteToList1 nanoAvg:1907243 memAvg:2026856
import java.util.ArrayList;
import java.util.List;
public class Test {
public static byte[] byteArray = new byte[0];
public static List<Byte> byteList = new ArrayList<>();
public static List<Double> nanoAvg = new ArrayList<>();
public static List<Double> memAvg = new ArrayList<>();
public static void addByteToArray1() {
// >>> SOLUTION ONE <<<
byte[] a = new byte[byteArray.length + 1];
System.arraycopy(byteArray, 0, a, 0, byteArray.length);
byteArray = a;
//byteArray = Arrays.copyOf(byteArray, byteArray.length + 1); // the same as System.arraycopy()
}
public static void addByteToList1() {
// >>> SOLUTION TWO <<<
byteList.add(new Byte((byte) 0));
}
public static void testAddByteToList1() throws InterruptedException {
System.gc();
long m1 = getMemory();
long n1 = System.nanoTime();
for (int i = 0; i < 100000; i++) {
addByteToList1();
}
long n2 = System.nanoTime();
System.gc();
long m2 = getMemory();
byteList = new ArrayList<>();
nanoAvg.add(new Double(n2 - n1));
memAvg.add(new Double(m2 - m1));
}
public static void testAddByteToArray1() throws InterruptedException {
System.gc();
long m1 = getMemory();
long n1 = System.nanoTime();
for (int i = 0; i < 100000; i++) {
addByteToArray1();
}
long n2 = System.nanoTime();
System.gc();
long m2 = getMemory();
byteArray = new byte[0];
nanoAvg.add(new Double(n2 - n1));
memAvg.add(new Double(m2 - m1));
}
public static void resetMem() {
nanoAvg = new ArrayList<>();
memAvg = new ArrayList<>();
}
public static Double getAvg(List<Double> dl) {
double max = Collections.max(dl);
double min = Collections.min(dl);
double avg = 0;
boolean found = false;
for (Double aDouble : dl) {
if (aDouble < max && aDouble > min) {
if (avg == 0) {
avg = aDouble;
} else {
avg = (avg + aDouble) / 2d;
}
found = true;
}
}
if (!found) {
return getPopularElement(dl);
}
return avg;
}
public static double getPopularElement(List<Double> a) {
int count = 1, tempCount;
double popular = a.get(0);
double temp = 0;
for (int i = 0; i < (a.size() - 1); i++) {
temp = a.get(i);
tempCount = 0;
for (int j = 1; j < a.size(); j++) {
if (temp == a.get(j))
tempCount++;
}
if (tempCount > count) {
popular = temp;
count = tempCount;
}
}
return popular;
}
public static void testCompare() throws InterruptedException {
for (int j = 0; j < 4; j++) {
for (int i = 0; i < 20; i++) {
testAddByteToArray1();
}
System.out.println("testAddByteToArray1\tnanoAvg:" + getAvg(nanoAvg).longValue() + "\tmemAvg:" + getAvg(memAvg).longValue());
resetMem();
for (int i = 0; i < 20; i++) {
testAddByteToList1();
}
System.out.println("testAddByteToList1\tnanoAvg:" + getAvg(nanoAvg).longValue() + "\t\tmemAvg:" + getAvg(memAvg).longValue());
resetMem();
}
}
private static long getMemory() {
Runtime runtime = Runtime.getRuntime();
return runtime.totalMemory() - runtime.freeMemory();
}
public static void main(String[] args) throws InterruptedException {
testCompare();
}
}
You can try below solution inside some class:
int[] a = {10, 20, 30, 40, 50, 61};
// private visibility - or change it as needed
private void resizeArray(int newLength) {
a = Arrays.copyOf(a, a.length + newLength);
System.out.println("New length: " + a.length);
}
It is not possible to resize an array. However, it is possible change the size of an array through copying the original array to the newly sized one and keep the current elements. The array can also be reduced in size by removing an element and resizing.
import java.util.Arrays
public class ResizingArray {
public static void main(String[] args) {
String[] stringArray = new String[2] //A string array with 2 strings
stringArray[0] = "string1";
stringArray[1] = "string2";
// increase size and add string to array by copying to a temporary array
String[] tempStringArray = Arrays.copyOf(stringArray, stringArray.length + 1);
// Add in the new string
tempStringArray[2] = "string3";
// Copy temp array to original array
stringArray = tempStringArray;
// decrease size by removing certain string from array (string1 for example)
for(int i = 0; i < stringArray.length; i++) {
if(stringArray[i] == string1) {
stringArray[i] = stringArray[stringArray.length - 1];
// This replaces the string to be removed with the last string in the array
// When the array is resized by -1, The last string is removed
// Which is why we copied the last string to the position of the string we wanted to remove
String[] tempStringArray2 = Arrays.copyOf(arrayString, arrayString.length - 1);
// Set the original array to the new array
stringArray = tempStringArray2;
}
}
}
}
Sorry, but at this time is not possible resize arrays, and may be never will be.
So my recommendation, is to think more to find a solution that allow you get from the beginning of the process, the size of the arrays that you will requiere. This often will implicate that your code need a little more time (lines) to run, but you will save a lot of memory resources.
We can't do that using array datatype. Instead use a growable array which is arrayList in Java.

How to check ensure a array does not contain the same element twice

I have a loop which assigns randomly generated integers into an array.
I need a way to ensure the same integer is not input into the array twice.
I figured creating a loop inside the overall loop would work but I am unsure on what to execute here.
int wwe[] = new int[9];
for(int i = 0; i < 9 ; i++){
int randomIndex = generator.nextInt(wwe.length);
wwe[i] = randomIndex;
System.out.println(wwe[i]);
System.out.println("########");
for(int j = 0; j < 9; j++){
System.out.println("This is the inner element " + wwe[j]);
}
}
If you want to enforce unique values, use a data structure meant for such a behavior, like a Set. TreeSet or HashSet would work perfectly.
You are actually looking for shuffling your array.
Note that what you really looking for is to find a random order of your array, this is called a permutation.
In java, it can be simply done using a list with Collections.shuffle().
If you are looking to implement it on your own - use fisher yates shuffle, it is fairly easy to implement.
Since other answers showed how to do it with Collections.shuffle() already - here is a simple implementation + example of fisher yates shuffle, that does not need to convert the original array into a list.
private static void swap (int[] arr, int i1, int i2) {
int temp = arr[i1];
arr[i1] = arr[i2];
arr[i2] = temp;
}
private static void shuffle(int[] arr, Random r) {
for (int i =0; i < arr.length; i++) {
int x = r.nextInt(arr.length - i) + i;
swap(arr,i,x);
}
}
public static void main(String... args) throws Exception {
int[] arr = new int[] {1 , 5, 6, 3, 0, 11,2,9 };
shuffle(arr, new Random());
System.out.println(Arrays.toString(arr));
}
Something similar to the following should meet your requirement.
It uses a HashSet to achieve unique elements.
Set<Integer> sint = new HashSet<>();
Random random = new Random();
while ( sint.size() < 9){
sint.add(random.nextInt());
}
For you example, you can use Collections.shuffle
public static void main(String[] args) {
List<Integer> a = new ArrayList<>(9);
for (int i = 0; i < 9; i++) {
a.add(i);
}
Collections.shuffle(a);
System.out.println(a);
}

Resize an Array while keeping current elements in Java?

I have searched for a way to resize an array in Java, but I could not find ways of resizing the array while keeping the current elements.
I found for example code like int[] newImage = new int[newWidth];, but this deletes the elements stored before.
My code would basically do this: whenever a new element is added, the array largens by 1. I think this could be done with dynamic programming, but I'm, not sure how to implement it.
You can't resize an array in Java. You'd need to either:
Create a new array of the desired size, and copy the contents from the original array to the new array, using java.lang.System.arraycopy(...);
Use the java.util.ArrayList<T> class, which does this for you when you need to make the array bigger. It nicely encapsulates what you describe in your question.
Use java.util.Arrays.copyOf(...) methods which returns a bigger array, with the contents of the original array.
Not nice, but works:
int[] a = {1, 2, 3};
// make a one bigger
a = Arrays.copyOf(a, a.length + 1);
for (int i : a)
System.out.println(i);
as stated before, go with ArrayList
Here are a couple of ways to do it.
Method 1: System.arraycopy():
Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array. A subsequence of array components are copied from the source array referenced by src to the destination array referenced by dest. The number of components copied is equal to the length argument. The components at positions srcPos through srcPos+length-1 in the source array are copied into positions destPos through destPos+length-1, respectively, of the destination array.
Object[] originalArray = new Object[5];
Object[] largerArray = new Object[10];
System.arraycopy(originalArray, 0, largerArray, 0, originalArray.length);
Method 2: Arrays.copyOf():
Copies the specified array, truncating or padding with nulls (if necessary) so the copy has the specified length. For all indices that are valid in both the original array and the copy, the two arrays will contain identical values. For any indices that are valid in the copy but not the original, the copy will contain null. Such indices will exist if and only if the specified length is greater than that of the original array. The resulting array is of exactly the same class as the original array.
Object[] originalArray = new Object[5];
Object[] largerArray = Arrays.copyOf(originalArray, 10);
Note that this method usually uses System.arraycopy() behind the scenes.
Method 3: ArrayList:
Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector, except that it is unsynchronized.)
ArrayList functions similarly to an array, except it automatically expands when you add more elements than it can contain. It's backed by an array, and uses Arrays.copyOf.
ArrayList<Object> list = new ArrayList<>();
// This will add the element, resizing the ArrayList if necessary.
list.add(new Object());
You could just use ArrayList which does the job for you.
It is not possible to change the Array Size.
But you can copy the element of one array into another array by creating an Array of bigger size.
It is recommended to create Array of double size if Array is full and Reduce Array to halve if Array is one-half full
public class ResizingArrayStack1 {
private String[] s;
private int size = 0;
private int index = 0;
public void ResizingArrayStack1(int size) {
this.size = size;
s = new String[size];
}
public void push(String element) {
if (index == s.length) {
resize(2 * s.length);
}
s[index] = element;
index++;
}
private void resize(int capacity) {
String[] copy = new String[capacity];
for (int i = 0; i < s.length; i++) {
copy[i] = s[i];
s = copy;
}
}
public static void main(String[] args) {
ResizingArrayStack1 rs = new ResizingArrayStack1();
rs.push("a");
rs.push("b");
rs.push("c");
rs.push("d");
}
}
You could use a ArrayList instead of array. So that you can add n number of elements
List<Integer> myVar = new ArrayList<Integer>();
Standard class java.util.ArrayList is resizable array, growing when new elements added.
You can't resize an array, but you can redefine it keeping old values or use a java.util.List
Here follows two solutions but catch the performance differences running the code below
Java Lists are 450 times faster but 20 times heavier in memory!
testAddByteToArray1 nanoAvg:970355051 memAvg:100000
testAddByteToList1 nanoAvg:1923106 memAvg:2026856
testAddByteToArray1 nanoAvg:919582271 memAvg:100000
testAddByteToList1 nanoAvg:1922660 memAvg:2026856
testAddByteToArray1 nanoAvg:917727475 memAvg:100000
testAddByteToList1 nanoAvg:1904896 memAvg:2026856
testAddByteToArray1 nanoAvg:918483397 memAvg:100000
testAddByteToList1 nanoAvg:1907243 memAvg:2026856
import java.util.ArrayList;
import java.util.List;
public class Test {
public static byte[] byteArray = new byte[0];
public static List<Byte> byteList = new ArrayList<>();
public static List<Double> nanoAvg = new ArrayList<>();
public static List<Double> memAvg = new ArrayList<>();
public static void addByteToArray1() {
// >>> SOLUTION ONE <<<
byte[] a = new byte[byteArray.length + 1];
System.arraycopy(byteArray, 0, a, 0, byteArray.length);
byteArray = a;
//byteArray = Arrays.copyOf(byteArray, byteArray.length + 1); // the same as System.arraycopy()
}
public static void addByteToList1() {
// >>> SOLUTION TWO <<<
byteList.add(new Byte((byte) 0));
}
public static void testAddByteToList1() throws InterruptedException {
System.gc();
long m1 = getMemory();
long n1 = System.nanoTime();
for (int i = 0; i < 100000; i++) {
addByteToList1();
}
long n2 = System.nanoTime();
System.gc();
long m2 = getMemory();
byteList = new ArrayList<>();
nanoAvg.add(new Double(n2 - n1));
memAvg.add(new Double(m2 - m1));
}
public static void testAddByteToArray1() throws InterruptedException {
System.gc();
long m1 = getMemory();
long n1 = System.nanoTime();
for (int i = 0; i < 100000; i++) {
addByteToArray1();
}
long n2 = System.nanoTime();
System.gc();
long m2 = getMemory();
byteArray = new byte[0];
nanoAvg.add(new Double(n2 - n1));
memAvg.add(new Double(m2 - m1));
}
public static void resetMem() {
nanoAvg = new ArrayList<>();
memAvg = new ArrayList<>();
}
public static Double getAvg(List<Double> dl) {
double max = Collections.max(dl);
double min = Collections.min(dl);
double avg = 0;
boolean found = false;
for (Double aDouble : dl) {
if (aDouble < max && aDouble > min) {
if (avg == 0) {
avg = aDouble;
} else {
avg = (avg + aDouble) / 2d;
}
found = true;
}
}
if (!found) {
return getPopularElement(dl);
}
return avg;
}
public static double getPopularElement(List<Double> a) {
int count = 1, tempCount;
double popular = a.get(0);
double temp = 0;
for (int i = 0; i < (a.size() - 1); i++) {
temp = a.get(i);
tempCount = 0;
for (int j = 1; j < a.size(); j++) {
if (temp == a.get(j))
tempCount++;
}
if (tempCount > count) {
popular = temp;
count = tempCount;
}
}
return popular;
}
public static void testCompare() throws InterruptedException {
for (int j = 0; j < 4; j++) {
for (int i = 0; i < 20; i++) {
testAddByteToArray1();
}
System.out.println("testAddByteToArray1\tnanoAvg:" + getAvg(nanoAvg).longValue() + "\tmemAvg:" + getAvg(memAvg).longValue());
resetMem();
for (int i = 0; i < 20; i++) {
testAddByteToList1();
}
System.out.println("testAddByteToList1\tnanoAvg:" + getAvg(nanoAvg).longValue() + "\t\tmemAvg:" + getAvg(memAvg).longValue());
resetMem();
}
}
private static long getMemory() {
Runtime runtime = Runtime.getRuntime();
return runtime.totalMemory() - runtime.freeMemory();
}
public static void main(String[] args) throws InterruptedException {
testCompare();
}
}
You can try below solution inside some class:
int[] a = {10, 20, 30, 40, 50, 61};
// private visibility - or change it as needed
private void resizeArray(int newLength) {
a = Arrays.copyOf(a, a.length + newLength);
System.out.println("New length: " + a.length);
}
It is not possible to resize an array. However, it is possible change the size of an array through copying the original array to the newly sized one and keep the current elements. The array can also be reduced in size by removing an element and resizing.
import java.util.Arrays
public class ResizingArray {
public static void main(String[] args) {
String[] stringArray = new String[2] //A string array with 2 strings
stringArray[0] = "string1";
stringArray[1] = "string2";
// increase size and add string to array by copying to a temporary array
String[] tempStringArray = Arrays.copyOf(stringArray, stringArray.length + 1);
// Add in the new string
tempStringArray[2] = "string3";
// Copy temp array to original array
stringArray = tempStringArray;
// decrease size by removing certain string from array (string1 for example)
for(int i = 0; i < stringArray.length; i++) {
if(stringArray[i] == string1) {
stringArray[i] = stringArray[stringArray.length - 1];
// This replaces the string to be removed with the last string in the array
// When the array is resized by -1, The last string is removed
// Which is why we copied the last string to the position of the string we wanted to remove
String[] tempStringArray2 = Arrays.copyOf(arrayString, arrayString.length - 1);
// Set the original array to the new array
stringArray = tempStringArray2;
}
}
}
}
Sorry, but at this time is not possible resize arrays, and may be never will be.
So my recommendation, is to think more to find a solution that allow you get from the beginning of the process, the size of the arrays that you will requiere. This often will implicate that your code need a little more time (lines) to run, but you will save a lot of memory resources.
We can't do that using array datatype. Instead use a growable array which is arrayList in Java.

Categories