I would appreciate some help with the code below:
// Remove last element
// Convert array to List for remove easily last item
List<String> listToRemove = new ArrayList<>(Arrays.asList(strings));
// Calculate index of last element & Remove them
int index = listToRemove.size();
index = index - 1;
System.out.println("Element to been removed: " listToRemove.get(index));
listToRemove.remove(index);
while(listToRemove.remove(null));
// This print works fine, without nulls ->
System.out.println(listToRemove);
// Coverting to an array & Print without last element
strings = listToRemove.toArray(strings);
// This print doesn't works fine, show nulls** ->
System.out.println(Arrays.toString(strings));
How could I write the last line so that they do not show nulls in the array?
CodePudding user response:
The problem with listToRemove.toArray(strings)
is that the length of strings
, which is too big, as you have removed items
Use a 0-length array because, the documentation is
the array into which the elements of this list are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.
strings = listToRemove.toArray(new String[0]);
// java 11
strings = listToRemove.toArray(String[]::new);
CodePudding user response:
If you want to increase the size of an already modified arraylist, you can use .ensureCapacity() method and also mentioning the size of the arraylist such as .ensureCapacity(15). The size will be 15 and hence the size is increased and to decrease the size, you can use trimToSize(), based on how many elements are present in your arraylist. It should shrink it's size to fit the present elements.