I need to clear the array list,Which one is better approach?Why?
Approach 1 :
List list = new ArrayList();
list.add("ram");
if(list!=null)
{
list.clear();
}
Approach 2:
List list = new ArrayList();
list.add("ram");
if(list!=null && !list.isEmpty())
{
list.clear();
}
In the approach 1, I don’t check whether list is empty or not,directly i have been clear the list.
But in the approach 2, i have been clear the list if the list is not empty by checking
if(list!=null && !list.isEmpty())
Which one is better approach?Approach 1 or approach 2?
It depends on the implementation, for ArrayList for example (this is its
clearmethod’s code):Means that the code doesn’t spend more time if the list is already empty. In this sense I would just clear the code as you did with the first approach.