24

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 new element is added to the array and the array becomes full, I want to update its size by '1'.

I tired various types of code, but it did not work out.

It would be of great help if someone could give me a solution regarding it - in code if possible.

Erik A
  • 31,639
  • 12
  • 42
  • 67
joel abishai paul
  • 247
  • 1
  • 2
  • 5
  • Refer this link, it will give some ideas [Array List](http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html) [Array Size](http://stackoverflow.com/questions/1647260/java-dynamic-array-sizes) – Nagaraj Sep 21 '12 at 04:42

12 Answers12

12

Instead of using an array, use an implementation of java.util.List such as ArrayList. An ArrayList has an array backend which holds values in a list, but the array size is automatically handles by the list.

ArrayList<String> list = new ArrayList<String>();
list.add("some string");

You can also convert the list into an array using list.toArray(new String[list.size()]) and so forth for other element types.

FThompson
  • 28,352
  • 13
  • 60
  • 93
  • Thanks....it..would be nice..if you can give me the code to print out ..the elements in the list – joel abishai paul Sep 21 '12 at 04:46
  • @joelabishaipaul `System.out.println(list)` should do the job just fine ;) If you want to print each one on a separate line, you can use a [for-each/enhanced-for loop](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html) to iterate over each value in the list. – FThompson Sep 21 '12 at 04:50
  • This doesn't address OP's original question, though it is a better solution to the problem. – TWhite Dec 01 '22 at 23:45
11

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.

A Kunin
  • 42,385
  • 1
  • 17
  • 13
8

You can create a temporary array with a size that is one element larger than the original, and then copy the elements of the original into the temp, and assign the temporary array to the new one.

public void increaseSize() {
   String[] temp = new String[original.length + 1];
   
   for (int i = 0; i < original.length; i++){
      temp[i] = original[i];
   }
   original = temp;
}

You can change the size in various ways, but the same idea applies.

Silly Freak
  • 4,061
  • 1
  • 36
  • 58
PandaOrb
  • 81
  • 1
  • 1
5

You can't. You can either create a new array and move the items to that array - Or you can use an ArrayList.

Peter Rasmussen
  • 16,474
  • 7
  • 46
  • 63
4

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];// Initializing array with zero
        int incrementLength = 1;
        for (int i = 0; i < data.length; i++) {
            array = Arrays.copyOf(data, i + incrementLength);// incrementing array by +1
        }
        /**
         * values of array after increment
         */
        for (String value : array) {
            System.out.println(value);
        }
    }
}

Output:

a
b
c
d
e
UdayKiran Pulipati
  • 6,579
  • 7
  • 67
  • 92
  • 1
    not going to edit this, as it would be a functional code change, but: this does not actually create a copy of `data` with increased size. It creates an empty array, and successively replaces that array with longer ones, finally arriving at an exact copy, not a longer one. The output shows this too: was the array longer, there should be a `null` output. To actually increase the length of the array, the declaration of `array` and the whole first loop should simply be replaced with `String[] array = Arrays.copyOf(data, data.length + incrementLength);`. – Silly Freak Jul 13 '21 at 11:27
2

https://www.java2novice.com/java-arrays/array-copy/

int[] myArr = {2,4,2,4,5,6,3};
System.out.println("Array size before copy: "+myArr.length);
int[] newArr = Arrays.copyOf(myArr, 10);
System.out.println("New array size after copying: "+newArr.length);

You can also do myArr = Arrays.copyOf(myArr, 10);

In this case do, myArr = Arrays.copyOf(myArr, myAry.length+1);

Apostolos
  • 10,033
  • 5
  • 24
  • 39
Harshal Karande
  • 476
  • 4
  • 9
0

u can use array list for that

here is example for array list of string

'import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList;

public class Ex01 {

public static void main(String[] args) throws IOException { 

    BufferedReader userInput = new BufferedReader 
        (new InputStreamReader(System.in));

    ArrayList<String> myArr = new ArrayList<String>();
    myArr.add("Italian Riviera");
    myArr.add("Jersey Shore");
    myArr.add("Puerto Rico");
    myArr.add("Los Cabos Corridor");
    myArr.add("Lubmin");
    myArr.add("Coney Island");
    myArr.add("Karlovy Vary");
    myArr.add("Bourbon-l'Archambault");
    myArr.add("Walt Disney World Resort");
    myArr.add("Barbados");

    System.out.println("Stupid Vacation Resort Adviser");
    System.out.println("Enter your name:");
    String name = userInput.readLine();
    Integer nameLength = name.length();
    if (nameLength == 0) 
    { 
        System.out.println("empty name entered");
        return;
    } 

    Integer vacationIndex = nameLength % myArr.size();

    System.out.println("\nYour name is "+name+", its length is " + 
                    nameLength + " characters,\n" +
                    "that's why we suggest you to go to " 
                    + myArr.get(vacationIndex));
} 

}'

similarly u can make array for integer,blooean and all kinds of data types

for more detail u can see this

http://www.anyexample.com/programming/java/java_arraylist_example.xml

Aamirkhan
  • 5,746
  • 10
  • 47
  • 74
0

Create list object, add the elements and convert that list object to array using list.toArray(new String[list.size()])

user1573029
  • 97
  • 1
  • 1
  • 6
0

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++;
       }             
    }   
  }

}
0

According to Oracle's Java Docs on Arrays, the size of an Array cannot be changed. Once it has been initialized, it is final. You cannot change it. The only way to make the size accommodate your elements is to create a new one with a bigger size or use other data structures like the ArrayList as mentioned in the solutions above. You initialize an array while at the same time keeping in mind the size of the elements you might want to store therein.

    //This declares an array of integers
     // which can hold a maximum of five integers
    int[] anArray = new int[5];

    //This declares an array of strings
     // which can hold a maximum of 20 strings
    String[] stringArray = new String[20];

   
-2
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);
}
}
-4

Use an ArrayList. The size it automatically increased if you try to add to a full ArrayList.

Osiris
  • 4,195
  • 2
  • 22
  • 52