0

Hi there,

In my little code snipet below I am trying to convert an arraylist to an array of type contact. Obviously it's expecting an arraylist of type contact to convert it to an array of type contact. But it's picking up the arraylist as type object for some reason.

public void readInfo(){
try{
    inputStream = new BufferedReader(new FileReader("conList.txt"));
}
catch(FileNotFoundException e){}

try{
    while ((conInfo = inputStream.readLine()) != null) {
         infoArray = conInfo.split("\\s+");

         //Create new Contact Object
         Contact newCon = new Contact(infoArray[0],infoArray[1],infoArray[2],
                                        infoArray[3],infoArray[4],infoArray[5]);

         //Add new Contact to ArrayList
         contactObj.add(newCon);

        MainList.add(infoArray[0]+" "+infoArray[1]); 
    }

    //Convert ArrayList to Array
    Contact ia[];
    ia = contactObj.toArray();// Error: incompatible types, 
                              // required: Contactkeeper.contact
                              // found: java.lang.Object[]

   }
   catch(IOException v){}


}

In my code you can see the comment on where the error is thrown and what error is thrown. Thank you so much for your help!

3
Contributors
5
Replies
6
Views
6 Years
Discussion Span
Last Post by Dean_Grobler
Featured Replies
  • 1

    Of course. Do you need it outside of the try block, though? Currently you have declared it within so it will go out of scope there, too. P.S. I [i]hope[/i] that that is not your [i]real[/i] catch block, though. Read More

0

Well, hopefully you declared and defined the ArrayList as ArrayList<Contact> and then you also need to to use the T[] form of the toArray method Contact[] ia = contactObj.toArray(new Contact[0]);

0

Yes I did declare it as ArrayList<Contact>. Cool, otherwise it is also right where I am not converting it to an array INSIDE the while loop. OUTSIDE the while loop is the place to do it hey?

1

Of course. Do you need it outside of the try block, though? Currently you have declared it within so it will go out of scope there, too.

P.S. I hope that that is not your real catch block, though.

0

After you have finished adding all the contacts, then convert it into array, outside the loop is the right place :)

EDIT: masijade beat me to it while I was typing :)

Edited by apines: n/a

0

hehe cool thanks guys. So outside the while loop, and outside the try block. And no lol, that's not my real catch, I'll add something in there at a later stage :-) Otherwise that's a million guys!

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.