0

If you create an array and declare its size, can I then change the size later if I under estimate how big I need it?

If you create an array and declare its size, can I then change the size later if I under estimate how big I need it?

12th Jun 2019, 9:31 AM
<htmlf>
<htmlf> - avatar
4 odpowiedzi
+ 1
In classic array like: int[] a = new int[3]; int[] b = new int[] {1,2,3,4,5}; you can assign new array to the same variable but old values will be lost; a[0] = 100; a = new int[6]; //old a[] with value 100 is lost b = new int[6]; System.out.println( "a="+Arrays.toString(a)); // a=[0, 0, 0, 0, 0, 0] System.out.println( "b="+Arrays.toString(b)); // b=[0, 0, 0, 0, 0, 0] but you can create a new array and copy old array there. ---------- ArrayList<>() : More comfortable is ArrayList<>(), where you can .add() elements over its size and array rises automatically. Or you can increase size with .addAll(). Its adds group of elements in one assign. ArrayList<String> als = new ArrayList<>(List.of("AB","CD","EF") ); // initialize // increase to new size als.addAll( Collections.nCopies(3, null) ); // newsize = size + 3 System.out.println( "als="+als); // als=[AB, CD, EF, null, null, null] System.out.println( "als.size()="+als.size()+"\n"); // als.size()=6 // decrease size int newSize = 3; als.subList(newSize, als.size() ).clear(); System.out.println( "als="+als); // als=[AB, CD, EF] System.out.println( "als.size()="+als.size()); // als.size()=3 // optionaly you can optimize memory after it with: als.trimToSize();
12th Jun 2019, 9:54 AM
zemiak
+ 4
You can't do that with a normal array, but you can use ArrayLists (part of the java.util package). https://www.geeksforgeeks.org/arraylist-in-java/amp/
12th Jun 2019, 9:50 AM
Owl Surojit
Owl Surojit - avatar
0
Thanks
12th Jun 2019, 9:52 AM
<htmlf>
<htmlf> - avatar
0
Thanks
12th Jun 2019, 10:22 AM
<htmlf>
<htmlf> - avatar