views:

36

answers:

4

If fooService.getFoos() returns List<Foo>.

then you can write this:

List<Foo> fooList = fooService.getFoos();

or this:

List<Foo> fooList = new ArrayList(fooService.getFoos());

Is there any significant difference in the resulting fooList between these two approaches?

+1  A: 

The second isn't really a good idea because you omit the generic part.

But the main problem is the unnecessary code which will be called. You can look at the ArrayList code source, and you'll see all the operations used in the constructor. If you only need a List, and fooService.getFoos() returns a valid List, you should stick with it.

The result of those two statement will be more or less the same unless:

  • later you check if your list is an instance of ArrayList and cast it, but let's face it, you would have declared ArrayList<Foo> if it was the case.
  • the list returned by fooService.getFoos() shouldn't be modified (for any reason) but you still want modify elements in the List on your side (without affecting the original list).

Resources :

Colin Hebert
A: 

I'd stick with the first one just because it reads lots easier and makes much more sense than the second one.

m0s
+1  A: 

Yes - you are creating a completely new List, containing the elements of the original one. You are duplicating the collection in memory, and iterating it from start to end. You are also not using instance provided by the service, and you can't modify the original. And finally, you've omitted the generics declaration in the 2nd snippet.

So use the first option.

Update: you indicated you are not allowed to modify the original list. This is actually a problem of fooService, not of its clients. If the service is also in your control, return Collections.unmodifiableList(originalList) - thus clients won't be able to perform modification operations (on attempt an exception will be thrown)

Bozho
modification is the issue - I'm not allowed to modify the list returned by getFoos. That's why I thought I should create a new ArrayList that I can modify.
zxc
@zcx - see my update about that.
Bozho
@Bozho: Cool. Thanks, man!
zxc
A: 

In the second statement it returns only of List type. If you are sure of method returning of same type den you can use firs type.

giri