I want to store as many elements as desired by the user in an array. But how do I do it.
If I were to create an array, I must do so with a fixed size. Every time a
By using copyOf method in java.util.Arrays
class String[]
size will increment automatically / dynamically. In below code array
size 0
after manipulation of using Arrays.copyOf
the size of String array
is increased to 4
.
package com.google.service;
import java.util.Arrays;
public class StringArrayAutoIncrement {
public static void main(String[] args) {
String[] data = new String[] { "a", "b", "c", "d", "e" };
String[] array = new String[0];// array initialize with zero
int incrementLength = 1;
for (int i = 0; i < data.length; i++) {
array = Arrays.copyOf(data, i + incrementLength);// increment by +1
}
/**
* values of array after increment
*/
for (String value : array) {
System.out.println(value);
}
}
}
Output:
a
b
c
d
e
On a low level you can do it this way:
long[] source = new long[1];
long[] copy = new long[source.length + 1];
System.arraycopy(source, 0, copy, 0, source.length);
source = copy;
Arrays.copyOf() is doing same thing.
Use an ArrayList. The size it automatically increased if you try to add to a full ArrayList.
u can do it by this
import java.util.Scanner;
class Add
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
char ans='y';
int count=0;
while(ans!='N'||ans!='n')
{
int initial_size=5;
int arr[]=new int [initial_size];
arr[0]=1;
arr[1]=2;
arr[2]=3;
arr[3]=4;
arr[4]=5;
if(count>0)
{
System.out.print("enter the element u want to add in array: ");
arr[initial_size-1]=obj.nextInt();
}
System.out.print("Do u want to add element in array?");
ans=obj.next().charAt(0);
if(ans=='y'||ans=='Y')
{
initial_size++;
count++;
}
}
}
}
public class IncreaseArraySize {
public static void main(String[] args) {
int arr[] = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = 5;
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println(" ");
System.out.println("Before increasing Size of an array :" + arr.length);
int arr2[] = new int[10];
arr = arr2;
arr2 = null;
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
System.out.println("After increasing Size of an array : " + arr.length);
}
}
You can't. You can either create a new array and move the items to that array - Or you can use an ArrayList.