File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes type casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "type casting" Watch "type casting" New topic
Author

type casting

Renu Radhika
Ranch Hand

Joined: Oct 21, 2005
Posts: 243
can an Arraylist be typecast to a vector?
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42263
    
  64
No. But they both extend AbstractList, so you can typecast to that.


Ping & DNS - my free Android networking tools app
Renu Radhika
Ranch Hand

Joined: Oct 21, 2005
Posts: 243
Thanks a lot
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
Originally posted by Ulf Dittmer:
No. But they both extend AbstractList, so you can typecast to that.

True, but note that AbstractList's public methods are precisely
the same as List's, so I would more likely write:

On the other hand, I think the OP wanted to *cast* ("convert*) an existing ArrayList
to a Vector: you can't do that, but you can create a new Vector that
holds copies of the references found in the ArrayList:

Note that v != arrayList, although v.equals(arrayList).

Of course, in the best of all possible worlds, just being of type List should suffice!


There is no emoticon for what I am feeling!
Stuart Ash
Ranch Hand

Joined: Oct 07, 2005
Posts: 637
I would mention two principles here that are useful:

1. Vector is old and kind of discouraged. Avoid its use unless there is legacy code which you must add your code to.

2. Use Collections 2 and always strive to use references of the base-interface type. E.g.,

List list = // new ArrayList();
public List getItems(){...}

This way, the implementation can be changed when needed.


ASCII silly question, Get a silly ANSI.
Stefan Wagner
Ranch Hand

Joined: Jun 02, 2003
Posts: 1923

A lot of classes in javax.swing expect a Vector in the constructor (or an array) but not an arraylist.
That's often a reason for using Vector.


http://home.arcor.de/hirnstrom/bewerbung
 
 
subject: type casting