[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 395
  • Last Modified:

Cannot cast keySet to String[] ?

Dear Experts:

Fascinating newbie question:  I'm loading a HashMap like this:

  myMap.put("A", 123);
  myMap.put("B", 456);

Then I'm trying to do:

String[] justMyKeys= (String[]) myMap.keySet().toArray();

And I'm getting a classcast exception.  I have this tingly feeling like I almost understand.  But not quite.

I know the "keySet" is just half a collection of Objects.  But if all I put in there is Strings, why can't I cast it to String[]?

Thanks!
BrianMc1958
0
BrianMc1958
Asked:
BrianMc1958
  • 4
  • 4
1 Solution
 
BrianMc1958Author Commented:
Or CAN I cast it to String[], but don't know how?
0
 
CEHJCommented:
You can find out what type it is by

System.out.println(myMap.keySet().toArray()[0].getClass());
0
 
CEHJCommented:
Sorry about that. It should be

String[] justMyKeys= (String[]) myMap.keySet().toArray(new String[0]);
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
CEHJCommented:
(You need to give the correct type to the method)
0
 
BrianMc1958Author Commented:
But that's the type of the first element, right?  I'm guessing my problem is in assuming I can cast the entire keySet as an array of one type.  Is there some reason (aside from type safety) that I can't?
0
 
BrianMc1958Author Commented:
Please disregard previous post.  I'm afraid I've asked (and you folks have answered) this same question in the past.  Thanks again...
0
 
BrianMc1958Author Commented:
If I ever get time, I'll go find the explanation.  It really was interesting...
0
 
CEHJCommented:
>>But that's the type of the first element, right?

That's the type of the array which you want to produce. That's what counts
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

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