-3

I wanted to use Dynamic Array in Java,

I will be declaring the array statically,where i will input values into the array ,once the array gets full i will reintialize the array size.

Whether the contents of the array will be removed or it will be maintained.

The contents are deleted in my program ,whether that is expected or not ? Example

class a
{
  static int arr[]=new int[10];
     arr[]={1,2,3,4,5};
      public static void main(String args[])
      {
         int N=35;
         arr=new int[N];
         arr[]={1....35};
      }

}
Renigunda
  • 45
  • 1
  • 9
  • 1
    What are you asking? Please refer to http://stackoverflow.com/help/asking to see how to ask questions on SO. – Maljam Apr 18 '16 at 04:42
  • 3
    Java arrays have a fixed length. How are you *reinitializing* the array? How can we know what your code does without seeing your code? Please *edit* your post into a [MCVE](http://stackoverflow.com/help/mcve). – Elliott Frisch Apr 18 '16 at 04:42
  • 3
    You could use an `ArrayList`. – Logan Apr 18 '16 at 04:43
  • Change `arr=new int[N]` to `arr=Arrays.copyOf(arr, N)`, if you want to maintain it. –  Apr 18 '16 at 04:55
  • Did you even compile and run this code? – isharailanga Apr 18 '16 at 05:01
  • Possible duplicate of [java dynamic array sizes?](http://stackoverflow.com/questions/1647260/java-dynamic-array-sizes) – Ani Menon Apr 18 '16 at 05:14

4 Answers4

4

Yes because when you think you're re-sizing it you're actually creating a new array with a different size. That is very much expected!!!

laish138
  • 243
  • 1
  • 2
  • 10
3

When you write:

arr=new int[N]

you actually discard your array object and create a new array of int of size N. This new object will not contain your previous array's values.

If you create a larger array, you must copy the previous values to it. Better still, use one of Java's data structures such as Vector<Integer> or ArrayList<Integer>. These use dynamic arrays, but you don't have to know about it and shouldn't worry - they just work...

Gilad
  • 833
  • 1
  • 8
  • 13
2

Better use arraylist, arraylist can grow which is not possible with arrays. if you to copy the contents into another array with different size use System.arraycopy() but previous array will exist. better way is using arraylist or vector

0

Arrays in Java are of fixed size. Use ArrayLists which is a collection & can dynamically scale.

Instead of

Integer[] ints = new Integer[x]

use

List<Integer> ints = new ArrayList<Integer>();
Ani Menon
  • 27,209
  • 16
  • 105
  • 126