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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

ArrayList method and casting? 1

Status
Not open for further replies.

jisoo22

Programmer
Apr 30, 2001
277
0
0
US
Hello,

I'm trying to use the BufferedWriter class to write files to a text file via an ArrayList of strings. Unfortunately I run into a compile-time error about not being able to resolve symbols. Is this a casting issue? Here's the snippet of code I have:

Code:
			FileWriter wr = new FileWriter(outFileName);
			BufferedWriter outFile = new BufferedWriter (wr);

			for(int i = 0; i < list.size(); i++)
			{
		  outFile.write(list.get(i));
		outFile.newLine();
			}

[code]

I think the &quot;get&quot; method returns an object, but I need a string to make this work.  Does anyone have any suggestions?

Thanks,
Jisoo22
 
I quick search of the JAva API documentation shows
Code:
public Object get(int index)
Returns the element at the specified position in this list.

and

Code:
public void write(String str)throws IOException

so your line
Code:
outFile.write(list.get(i));
is trying to pass an
Code:
object
to a
Code:
String
argument.


you will need to cast what .get returns into a string so that .write can write it. -------------------------------------------
There are no onions, only magic
-------------------------------------------
 
Actually, it should be:

Object obj = list.get(i);
String myString = (String)obj;
outFile.write(myString);

However, since every object has a toString method, this is much simpler:

outFile.write(list.get(i).toString());
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top