Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

String[] array = notSortedVector.toArray(); This is not working!!!

Status
Not open for further replies.

Guy1983

Programmer
Jan 7, 2005
13
US
Hi,

String[] array = notSortedVector.toArray();

I get an incompatible types compilation error for this line of code. Does anyone have any clue why??

Any help would be greatly appreciated.

Thank you very much

Guy
 
You don't say what type "notSortedVector" is ... but I am guessing it is a Vector. If you read the documentation for Vector ( ), you would see that the toArray() method returns a Object[], not a String[].

Of course, the compiler debug would also have told you this :

Code:
found   : java.lang.Object[]
required: java.lang.String[]

So you should either use :

Code:
Object[] arr = vector.toArray();
or cast :
Code:
String[] arr = (String[])vector.toArray();

--------------------------------------------------
Free Database Connection Pooling Software
 
Hi Sedj,

I tried
String[] arr = (String[])vector.toArray();

I got a runtime error pointing to that line saying:

Exception in thread "main" java.lang.ClassCastException

I do know that the object[] = .... would work but I don't want to have to do that. The goal of my method is to sort a vector of strings alphabetically. I am passing the method a vector. I then want to convert it to an array. Use the arrays built-in sort algorithms to sort the array and then put the items back into a vector in sorted order and return it.

Thank you

 
First of all, check that the elements stored in the Vector are Strings (imaging that vector is a java.util.Vector).

If so, do this

Code:
String[] runtimeType = new String[]{};
String[] array = vector.toArray(runtimeType);

Cheers,

Dian
 
I believe you can just sort the Vector itself. Try this:

Collections.sort(vector);

It will sort the Strings in ascending alphabetical order.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top