开发者

Java: How to reset an arraylist so that it is empty [closed]

开发者 https://www.devze.com 2023-04-11 08:55 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 10 years ago.

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>();

    //Lis开发者_运维问答t<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);
    }
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消