• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 265
  • Last Modified:

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

0
R6
Asked:
R6
  • 2
1 Solution
 
StillUnAwareCommented:
You must cast the type back:

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

ArrayList<A> al = new ArrayList<A>();
...
A a = al.get(i);
0
 
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
0
 
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
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now