Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

type casting

 
Renu Radhika
Ranch Hand
Posts: 243
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can an Arraylist be typecast to a vector?
 
Ulf Dittmer
Rancher
Pie
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No. But they both extend AbstractList, so you can typecast to that.
 
Renu Radhika
Ranch Hand
Posts: 243
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
Stuart Ash
Ranch Hand
Posts: 637
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Stefan Wagner
Ranch Hand
Posts: 1923
Linux Postgres Database Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic