simple ArrayList question!

hi experts,

basically, i want to create an arraylist of user defined class, in this case, an arraylist of A as illustrated below.  the problem occurs after i have initialized the arraylist and i want to get the inidividual element out of it, i have encountered an incompatible type error as illustrated below.

can someone explain this to me?

many thanks

r6


------------------
Class A {
  ...
  ...
}

Class State {
  ArrayList al = new ArrayList();
  ...
  ...
  A a = new A();
  al.add(a);
  ....
  void somefunction() {
    ...
    A a = al.get(i);  // Incompatible types error!!!!!
    ...
}
 

R6Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

StillUnAwareCommented:
You must cast the type back:

A a = (A)al.get(i);
StillUnAwareCommented:
Or use generics (since Java 5.0):

ArrayList<A> al = new ArrayList<A>();
...
A a = al.get(i);

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
CEHJCommented:
If you're using >= 1.5 you can use generics to avoid typecasting and introduce compile time type safety:

class State {
  ArrayList<A> al = new ArrayList<A>();
 
  ...
}

A a = al.get(i);

is then possible
R6Author Commented:
well thanks StillUnAware and CEHJ for the rapid responses:) i really appreciate it.

not only have i learnt the solution to my problem, i've also realized that i was compiling with java 1.4.2..took me a while to reset the path to 1.5 on mac.. and i finally know what <E> stands for on the API.

thanks again
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.