See the documentation for ArrayList#remove(int), as in the following syntax:
list.remove(list.size() - 1)
Here is how it's implemented. elementData does a lookup on the backing array (so it can cut it loose from the array), which should be constant time (since the JVM knows the size of an object reference and the number of entries it can calculate the offset), and numMoved is 0 for this case:
public E remove(int index) {
rangeCheck(index); // throws an exception if out of bounds
modCount++; // each time a structural change happens
// used for ConcurrentModificationExceptions
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // Let gc do its work
return oldValue;
}
Answer from Nathan Hughes on Stack OverflowSee the documentation for ArrayList#remove(int), as in the following syntax:
list.remove(list.size() - 1)
Here is how it's implemented. elementData does a lookup on the backing array (so it can cut it loose from the array), which should be constant time (since the JVM knows the size of an object reference and the number of entries it can calculate the offset), and numMoved is 0 for this case:
public E remove(int index) {
rangeCheck(index); // throws an exception if out of bounds
modCount++; // each time a structural change happens
// used for ConcurrentModificationExceptions
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // Let gc do its work
return oldValue;
}
Since Java 21, simply using List.removeLast, for example:
List<Integer> list = new ArrayList<>(List.of(1, 2, 3));
System.out.println(list.removeLast()); // 3 - removes and returns the last element
Note: if the list is not empty, the implementation of List.removeLast returns the result of calling remove(size() - 1). Otherwise, it throws NoSuchElementException.
The time complexity of removing the last element from ArrayList is O(1) - it is just decrementing the size of the list by 1 under the hood.
arraylist - Remove Last Element from a List in Java - Stack Overflow
Java* Add the removeLast method to
the ArrayList class of Section 16.4. Return the removed
element or null if the array list is empty.
ArrayList.java
/**
This is a simplified implementation of an array
list.
*/
public class ArrayList
{
private Object[] elements;
private int currentSize;
/**
Constructs an empty array list.
*/
public
provide a removelast method for the arraylist implementation above that removes the last element. if the current size is more than 25 percent full, the method sunoly removes the last
Java - remove last known item from ArrayList - Stack Overflow
tl;dr
pathToFile.getParent()
Path#getParent
No need to resort to crude string manipulation. Java NIO abstracts us away from the platform-specific details.
Call Path#getParent to get another path object while dropping the last element of the original.
Path pathToFile = Paths.get( "SomeFolder" , "SomeFile" ) ;
Path pathToFolder = pathToFile.getParent() ;
List#removeLast
By the way, to answer the title of your Question…
In Java 21+, List is a sub-interface of SequencedCollection. This brings convenient new methods such as removeLast.
myList.removeLast() ;
Actually, you might be getting the UnsupportedOperationException, this is happening because you have used the Arrays.asList method, by using which the list cannot be modified i.e. no elements can be added or removed from the path list.
So, to perform your desired operation, you can use the below code.
String[] pathArray = Paths.get("").toAbsolutePath().toString().split("\\\\");
List<String> path = new ArrayList<>();
Collections.addAll(path, pathArray);
System.out.println(path);
int removeJavaFile = path.size() - 1;
path.remove(removeJavaFile);
System.out.println("Path: "+path);
String filePath = path.stream().map(n -> String.valueOf(n)).collect(Collectors.joining("\\\\"));
System.out.println(filePath);
Here, first you get the pathArray and then add those array elements into a list which can be modified which makes you remove the last element from the list.
It should be:
ClientThread hey = clients.get(clients.size() - 1);
clients.remove(hey);
Or you can do
clients.remove(clients.size() - 1);
The minus ones are because size() returns the number of elements, but the ArrayList's first element's index is 0 and not 1.
The compiler complains that you are trying something of a list of ClientThread objects to a String. Either change the type of hey to ClientThread or clients to List<String>.
In addition: Valid indices for lists are from 0 to size()-1.
So you probably want to write
String hey = clients.get(clients.size()-1);
Edit: Solved
It's much more flexible to use generic lists instead of arrays. Arrays are immutable and should not be used when there is a need to add or remove elements. Another option is to use array lists, but others reported that they are deprecated and that generic lists should be used instead.
Thank you all for the help!
-------------
PowerShell 7, an array like $array = @()
Like the title say - is there?
The solutions I've found online are all wrong.
- Array slicing
$array = $array[0..($array.Length - 2)]
This does not work if the array length is 1, because it resolves to $array[0..-1]. Step-by-step debugging shows that instead of deleting the last remaining element of the array, it will duplicate that element. The result will be an array of 2 elements, not 0.
- Select-Object
$array = $array | Select-Object -SkipLast 1
This does not work well with Hashtables as array elements. If your array elements are Hashtables, it will convert them to System.Collections.Hashtable. Hashtable ($example = @{}) and System.Collection.Hashtable are not the same type and operations on those two types are different (with different results).
Edit for the above: There was a typo in that part of my code and it returned some nonsense results. My bad.
- System.Collections.ArrayList
Yes, you can convert an array to System.Collection.ArrayList, but you are then working with System.Collections.ArrayList, not with an array ($array = @()).
----------------
One solution to all of this is to ask if the array length is greater than one, and handle arrays of 1 and 0 elements separately. It's using an if statement to simply remove the last element of an array, which is really bad.
Another solution is to loop through an array manually and create a new one while excluding the last element.
And the last solution that I've found is not to use arrays at all and use generic lists or array lists instead.
Is one of these options really the only solution or is there something that I'm missing?
List indices go from 0 to list.size() - 1. Exceeding the upper bound results in the IndexOutOfBoundsException
list.remove(list.size() - 1);
List#removeLast
As of Java 21, you can now use removeLast().
Removes and returns the last element of this collection (optional operation).
https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/List.html#removeLast()
You are getting IndexOutOfBounds because you are trying to remove an item that isn't there, so you should perform a check on your removal to stop the removal if there is nothing there:
if(array.size() > 0){
array.remove(array.size() -1);
}
You have an empty array as @TheAndroidDev said. What about to use Rx, something like this:
Observable.from(array)
.interval(10, TimeUnit.MINUTES)
.map(i -> array.size() > 0 ? array.remove(array.size() - 1) : null)
.take(array.size())
.subscribe(integer -> {
// Do something with the integer or type you use
});