Link to home
Start Free TrialLog in
Avatar of R6
R6

asked on

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!!!!!
    ...
}
 

Avatar of StillUnAware
StillUnAware
Flag of Lithuania image

You must cast the type back:

A a = (A)al.get(i);
ASKER CERTIFIED SOLUTION
Avatar of StillUnAware
StillUnAware
Flag of Lithuania image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of CEHJ
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
Avatar of R6
R6

ASKER

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