0

I was in need of a dynamic "database" of objects and after some research, decided to use ArrayList. However, I cannot modify the arraylist with the code as follows:

public static ArrayList cprofiles;
...
cprofiles = new ArrayList();
...
...
Customer newc = new Customer (lna, fna, sinum, year, month, day);
cprofiles.add (newc);

After this declaration, I am trying to call to methods within the object using the following format cprofiles.get(0).getName() but I am getting an error stating

cannot find symbol (pointing to .getName())

when I try to compile the program. I have spent about an hour researching the proper method to modify this in an ArrayList but the sources I have found seem to suggest that I what I am doing is indeed correct. Please aid me spotting my error and how I may fix it.

Thanks!

2
  • 2
    It might also be that cprofiles.get(0) need to be casted (or the list to be new ArrayList<Customer>()). Commented Oct 21, 2012 at 14:54
  • 1
    or public static ArrayList<Customer> cprofiles Commented Oct 21, 2012 at 14:56

1 Answer 1

6

You should use the generic version of ArrayList, and not the raw version:

List<Customer> cprofiles = new ArrayList<Customer>();

If you just use ArrayList, the compiler doesn't know what your list contains, so everything is considered as an Object. And you thus need to cast the returned object to its actual type:

Customer c = (Customer) list.get(0);
4
  • Ah damn. How did I miss that. Thought he had declared an ArrayList with the type parameter. Haste makes waste :) Commented Oct 21, 2012 at 14:56
  • @bot you mean "haste makes waste"? Commented Oct 21, 2012 at 14:58
  • Proved that point once again. :). Auto correct on mobile phone keyboards can sometimes be a pain. Commented Oct 21, 2012 at 14:58
  • Semi-related question: Can Collections.sort() now be applied to the name in each object? If so, what would be the syntax for this? Commented Oct 21, 2012 at 16:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.