• Post Reply Bookmark Topic Watch Topic
  • New Topic

need help on returning List from Vector  RSS feed

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am creating a Vector in the method and returning List instead of vector.
For ex:

public List test() {
Vector v = new Vector(0);
for(int i=0; i<5; i++) {
v.addElement(new Integer(1));
}
return v;
}

In the above method the return type is List but the actual return value is Vector.
Is there any harm if I do like that?

Thanks.
 
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by madukar chemakuriti:
...the return type is List but the actual return value is Vector. Is there any harm if I do like that? ...

A Vector is a List. The runtime type of the object is Vector, and the reference returned by the method is upcast to type List.

Actually, this is probably a good thing, because your method can return any type of List. So if you later need to change the implementation to create an ArrayList instead of a Vector, the method can still return a List, as expected by the callers.

PS: Using CODE tags will keep your code formatting intact.
[ November 02, 2005: Message edited by: marc weber ]
 
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to add some strength to Marc's "probably." It's absolutely a good thing, a wonderful thing, for the reasons he describes. Use interfaces as method return types and as method argrument types whenever you can, and you will eventually be very glad you did!
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ernest Friedman-Hill:
I want to add some strength to Marc's "probably." It's absolutely a good thing...

Okay, I do tend to over-qualify things. :roll:

When I used that word, I was imagining other code already in place that takes the reference returned by the method and downcasts it to type Vector without first checking the actual runtime type.

But yes, it's absolutely a good thing. (Uh... In the broader sense, that is.)
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!