Solved

class HashSet

Posted on 2002-04-15
3
330 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
  • 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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

762 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

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now