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

class HashSet

I insert some instances of class A to HashSet . When I try to access them with Iterator I get an instance of class Object and not of class A. How can I solve this problem?
  • 2
1 Solution
You must cast the result to Class A as in:
ClassA s = (ClassA)iterator.next()
Jim CakalicSenior Developer/ArchitectCommented:
Did you try simply downcasting the returned objects? Example:

    HashSet hash = new HashSet();
    hash.add(new A());
    Iterator iter = hash.iterator();
    while (iter.hasNext()) {
        A each = (A)iter.next();

Your objects haven't changed type. It is simply that the collections are not type-specific so they accept and return all members as type Object. You can still downcast to the specific type safely -- assuming that your collections are homogeneous.

Best regards,
Jim Cakalic
Hmm. I'm getting a feeling of deja vu!
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

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

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