I have an arraylist<interface>
Objects get added to this list in a for loop. I would like this arraylist to be empty each time the method is called.
Here is the code:
The array I want to empty here is suggestedPhrases.
public List<Interface> returnSuggestedList(String prefix) {
String tempPrefix = prefix;
// suggestedPhrases = null;
//suggestedPhrases = new ArrayList<Interface>();
//Vector<String> list = new Vector<String>();
//List<Interface> interfaceList = new ArrayList<Interface>();
Collections.sort(wordsList);
System.out.println("Sorted Vector contains : " + wordsList);
int i = 0;
//List<String> selected = new ArrayList<String>();
for(String w:wordsList){
System.out.println(w);
if(w.startsWith(prefix.toLowerCase())) { // or .contains(), depending on
//selected.add(w); // what you want exactly
Item itemInt = new Item(w);
suggestedPhrases.add(itemInt);
}
}
We can use ArrayList. clear() or ArrayList. removeAll() method to empty an ArrayList. The clear() method is the fastest as it only set the reference to the underlying array as null while the removeAll() will perform some additional work.
clear() method removes all of the elements from this list. The list will be empty after this call returns.
clear() deletes every element from the collection and removeAll() one only removes the elements matching those from another Collection.
This question already has answers here: And I add all the objects to an ArrayList and then pass it to that method: ArrayList toClean = new ArrayList<Object>(); toClean. add(obj1); toClean. add(obj2); checkAndClean(toClean);
If the array persists across calls to your method (e.g. if it's a member of the class), you can call suggestedPhrases.clear()
to clear it.
From your example there's doesn't appear to be any need to persist suggestedPhrases
across calls, so you can simply create (and return) a new array list every time your method is called:
public List<Interface> returnSuggestedList(String prefix) {
ArrayList<Interface> suggestedPhrases = new ArrayList<Interface>();
// populate suggestedPhrases here
return suggestedPhrases;
}
You can call the clear
method, but normally I prefer creating a new instance instead of re-using an existing one. The overhead is negligible (except for really performance-critical sections) as today's JVMs can handle object re-allocation quite well.
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