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!

copying from vector to array 2

Status
Not open for further replies.

OhioSteve

MIS
Mar 12, 2002
1,352
US
I normally work with asp.net, but I have been drafted to do some work on a java legacy app. I want to copy from a vector to an array. This is my code:

String[] myOutput = new String[myVector.size()];
myOutput = myVector.toArray(String[] myOutput);

The compiler says ".class expected" on the second line. Please advise.
 
In the toArray() method, you try to instantiate a new myOutput, when you defined it on the previous line.

Instead, it should be:
myOutput = myVector.toArray(myOutput);
Here is a test program I wrote that works.

Code:
import java.util.Vector;

public class Test
{
	public static void main(String args[])
	{
		Vector myVector = new Vector();
		String[] myOutput;
		
		for(int i = 0; i < 10; i++)
		{
			myVector.add(i + "");
		}

		myOutput = new String[myVector.size()];
		
		// You must cast the result into a String array, since it is currently
		// an array of objects.
		myOutput = (String[])myVector.toArray(myOutput);
		
		for(int j = 0; j < myOutput.length; j++)
		{
			System.out.println("Value " + j + ": " + myOutput[j]);
		}
		System.exit(0);
	}	
}

Nick Ruiz
Webmaster, DBA
 
Thanks for the quick response!

I tried your code and it worked. Then I tried to make my function match your suggestions. Unfortunately, the compiler still complained. I got this message:

alliedSales.java.204.incompatible types
found: java.lang.Object[]
required:java.lang.String[]
myOutput= myVector.toArray(myOutput);

Any suggestions?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top