Home > Back-end >  The Set interface object toArray () method.
The Set interface object toArray () method.

Time:11-28

Check API, toArray () method returns the Object array Object, incredibly is Object, the level is too high, the Object type shouldn't follow the key types of hasmap? Don't because keySet () method to Object types is converted to Object? The keySet () is not enough friend,
 import Java. Util. *; 

Public class iterator {
Public static void main (String [] args) {
HashMap A hashmap=new HashMap<> (a);
Hashmap. Put (" 1 ", 1);
Hashmap. Put (" 2 ", 2);
The Set keyset=hashmap. Keyset ();
Object [] keys.=keyset toArray ();
System. The out. Println (keys) getClass ());
}
}

CodePudding user response:

Set inside the collection deposit is of type Object

CodePudding user response:

You should write
so
 Set Keyset=hashmap. Keyset (); 
String [] keys=new String [keyset size ()];
Keyset. ToArray (keys);

CodePudding user response:

ToArray can be to return a composed of these Object Object array,
HashSet class provides toArray another overloaded versions, allowing the user to specify a than Object [] array of more specific types, the method is to pass a users want an array type of instances in an array

CodePudding user response:

Because the inside of the HashMap key values for type are generic, so the source code at first did not know you will hold what types of data, so they can only turning him up into the root node types (type Object), but the user know type, so can go to the second floor of that kind of writing

CodePudding user response:

refer to the second floor of green _ reply:
you should write
 Set Keyset=hashmap. Keyset (); 
String [] keys=new String [keyset size ()];
Keyset. ToArray (keys);


Thank you, but the idea is recommended I wrote:
 
The Set keyset=hashmap. Keyset ();
String [] keys=(String []) keyset. ToArray ();

CodePudding user response:

reference 5 floor qq_16774199 reply:
Quote: refer to the second floor of green _ a reply:
you should write
 Set Keyset=hashmap. Keyset (); 
String [] keys=new String [keyset size ()];
Keyset. ToArray (keys);


Thank you, but the idea is recommended I wrote:
 
The Set keyset=hashmap. Keyset ();
String [] keys=(String []) keyset. ToArray ();

I think you write so called the warning, certainly did not make good use of generics, keyset directly above is the Set of the original type, directly under the strong

CodePudding user response:

It should be a LZ will not use, not a keySet not enough friends

 import Java. Util. *; 

Public class iterator {
Public static void main (String [] args) {
HashMap A hashmap=new HashMap<> (a);
Hashmap. Put (" 1 ", 1);
Hashmap. Put (" 2 ", 2);
Set Keyset=hashmap. Keyset ();
String [] keys=keyset. ToArray (new String [0]).
System. The out. Println (keys) getClass ());
}
}
  • Related