HashMap<Teacher,Student> one = new HashMap<>();//Teacher,student都是自定义的类
one.put(wang,wan);//one.put(Teacher,Student)
应该如何获取hashMap.key
我google了发现一些做法但是都没有什么用
例如
Teacher[] i = one.keyset().toArray(new Teacher[0]);
我想问一下如何获取key同时可以新定义一个对象来引用key
主要我无法解决的是one.keyset().toArray(new Teacher[0])
返回的是一个超类,我没有办法强制转化,希望可以给我一点提示或者解决的方法,java新手。
The toArray method body uses forced type conversion, which is based on the type you pass in. Your
directly.new Teacher[0]
is used to transfer types, so for reuse, it is recommended to writeIn this way, the array passed in will be filled and then returned, which is more efficient.
toArray returns an array
For obtaining hashkey, please consult the API documentation yourself. Being familiar with jdk is very important for learning java. I guarantee there is such a method in jdk. You can consult the documentation for hashmap or its parent class.
About this definition:
If it were me, I would choose:
The former definition will cause the loss of type information. You must force conversion to get the type you want, and it is very unsafe. This also violates the original intention of generic design.
Above.
This is what I did
The reason why I have been wrong before may be that there was a type loss error when using map. I have only seen this part of generics. Thanks for pointing out the error @驽马