-1
   public static int test() {
  String [] empty = new String[10];
 methodname(empty);
 }

 public static int methodname(String[] set) {
  int a = set.length // it would be 10 but is there anyway I can modify this whatever number I desire?
   }

As I mentioned, I want to change the given array length w/o creating a new one. Is it possible?

+I am not suppose to import anything.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Ddnsnxe2
  • 75
  • 5
  • 7
    No, you can't. When an array has been created, its length is fixed. – Jon Skeet Jun 30 '21 at 19:01
  • What you ask for is impossible, but for alternatives maybe check out [Resize an Array while keeping current elements in Java?](https://stackoverflow.com/q/13197702/3890632) – khelwood Jun 30 '21 at 19:09

3 Answers3

1

That's impossible - you can't redefine array's length in Java. In order to achieve your goal you can use a wrapper class java.util.ArrayList which is implementation of dynamic array.

0

No, we cannot change array size in java after defining. Note: The only way to change the array size is to create a new array and then populate or copy the values of existing array into new array or we can use ArrayList instead of array

anish sharma
  • 568
  • 3
  • 5
0

You can't modify the size of an existing one but you can reassign a new array to the same variable. You can do it like this.


int[] array = {1,2,3,4};
int newLength = 8;
System.out.println(Arrays.toString(array));
array = java.util.Arrays.copyOf(array,newLength);
System.out.println(Arrays.toString(array));

prints

[1, 2, 3, 4]
[1, 2, 3, 4, 0, 0, 0, 0]

If the newLength is shorter, the end items will be omitted. If it is longer, all the existing items will be copied to an array of the new length.

If you want to have a data structure that dynamically increases in size as needed, then use an ArrayList

WJS
  • 36,363
  • 4
  • 24
  • 39