Solved

class HashSet

Posted on 2002-04-15
3
336 Views
Last Modified: 2010-03-31
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?
0
Comment
Question by:Afifior
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 6942595
You must cast the result to Class A as in:
ClassA s = (ClassA)iterator.next()
0
 
LVL 19

Accepted Solution

by:
Jim Cakalic earned 50 total points
ID: 6942600
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
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 6942655
Hmm. I'm getting a feeling of deja vu!
0

Featured Post

Transaction Monitoring Vs. Real User Monitoring

Synthetic Transaction Monitoring Vs. Real User Monitoring: When To Use Each Approach? In this article, we will discuss two major monitoring approaches: Synthetic Transaction and Real User Monitoring.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…

688 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question