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!

ArrayList add and get problems. 2

Status
Not open for further replies.

Miros

Programmer
Jan 27, 2001
506
US
I have a class I defined, MyObject, and I want to create an ArrayList of this class. The add works fine:
[pre]
data.add( new myobject( ) ) ;
[/pre]

But when I try to get this way:
[pre]
MyObject mo = data.get( row ) ;
[/pre]

I get a compile time "incompatible types" error.

Does anyone know how to resolve this?

Rose/Miros
 
Found the answer!

Thanks Diancecht!

Silly question, did you play DragonRealms in another life?
 
I played online this life for a long time, but not DragonRealms, maybe in another life :)

Glad you got your problem solved.

Btw, if you're running Java 1.5 and you're populating the ArrayList only with objects of your class, you can consider the use of generics.

Cheers,
Dian
 
For anyone else reading this post :

In Java version below 1.5, one is required to cast the object from the ArrayList :

Code:
MyObject mo = (MyObject)arrayList.get(i);

In Java 1.5, if you define ArrayList as :

Code:
ArrayList list = new ArrayList();

then a cast (as above) is still required.
However, the cast is not required in 1.5 if you use generics, and declare your ArrayList as :

Code:
ArrayList<MyObject> list = new ArrayList<MyObject>;

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Oh thanks! That's that template stuff I need to learn someday...

Anyone know of a good reference book?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top