We are given a list of words in the form of an ArrayList as follows:
public ArrayList<String> getListOfStrings(){
ArrayList<String> list = new ArrayList<String>();
list.add("This");
list.add("is");
list.add("an");
list.add("exercise");
list.add("to");
list.add("illustrate");
list.add("the");
list.add("use");
list.add("of");
list.add("ArrayLists");
list.add(".");
return list;
}
How do I write a method that removes all words in that list (i.e. all the objects in the ArrayList) that have the length "len" entered by the user?
I already wrote a method that lists all the words of length "len" entered by the user, and it works, it's as follows:
public ArrayList<String>getWordsWithLength(int len, ArrayList<String> lijst){
ArrayList<String> list = new ArrayList<String>();
for(String woord: lijst){
if(woord.length()==len){
list.add(woord);
}
}
return(list);
}
But as a beginner in java, I'm stuck on how to remove the words of length "len". Please help! (I am under the impression that you start by removing them from the end of the list, back-to-front as it were)
remove() Method. Using the remove() method of the ArrayList class is the fastest way of deleting or removing the element from the ArrayList. It also provides the two overloaded methods, i.e., remove(int index) and remove(Object obj).
Java List remove() method is used to remove elements from the list.
Answer: Java does not provide a direct method to remove an element from the array. But given an index at which the element is to be deleted, we can use ArrayList to remove the element at the specified index. For this, first, we convert the array to ArrayList and using the remove method we remove the element.
The . remove() method is used for removing specified elements from instances of the ArrayList class.
The way your currently iterating through the list wont allow you to remove it with an exception but an iterator would.
Iterator<String> it = list.iterator();
while(it.hasNext()) {
if([Condition]) {
it.remove();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With