Reputation: 3989
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?
Upvotes: 3
Views: 181
Reputation: 2242
Initialize the list again.
List list = new ArrayList();
list.add("ram");
if(list!=null && !list.isEmpty())
{
list = new ArrayList();
}
Upvotes: 0
Reputation: 143876
It doesn't matter. The overhead of clear()
vs a check against isEmpty()
is 1 line of code, a modcount++;
Upvotes: 2
Reputation: 25613
As for the source code of clear()
it does not check if the collection is empty or not.
public void clear() {
modCount++;
// Let gc do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
But this is a very little optimization, I guess you should take care of this only if you are having performance problems.
You can use both versions, and anyway if the list is not empty you wanted to clear it, and if the list is empty, then the clear() method will be very quick to execute, so... Don't bother
Upvotes: 2
Reputation: 23903
It depends on the implementation, for ArrayList for example (this is its clear
method's code):
public void clear() {
modCount++;
// Let gc do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
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.
Upvotes: 4
Reputation:
Since ArrayList
is array-based, you don't need to check whether is it empty or not. Therefore, I favourite the first approach because of its "micro" high performance
Upvotes: 1
Reputation: 5699
Number one, try to use generics:
List<String> list = new ArrayList<String>();
list.add("ram");
Since it's initialized now, there is no need for null checks.
Now, if there is a specific contract you need to uphold to, you can check if the list is not empty, but as @Puce said, it's micro optimization.
list.clear();
Upvotes: 7
Reputation: 38132
It depends how clear()
is implemented. This is a micro optimization at the most, so I recommend not to spend too much time thinking about this.
Upvotes: 1