java - hashmap如何获取键值?
迷茫
迷茫 2017-04-17 15:30:36
0
4
603
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新手。

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(4)
小葫芦

The toArray method body uses forced type conversion, which is based on the type you pass in. Your new Teacher[0] is used to transfer types, so for reuse, it is recommended to write

directly.
HashMap<Teacher,Student> map = new HashMap<>();//Teacher,student都是自定义的类
...
Set<Teacher> set = map.keySet();
Teacher[] teachers = set.toArray(new Teacher[set.size()])

In this way, the array passed in will be filled and then returned, which is more efficient.

刘奇
Teacher[] i = one.keyset().toArray(new Teacher[0]);

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:

HashMap<Teacher,Student> one = new HashMap<>();//Teacher,student都是自定义的类

If it were me, I would choose:

HashMap<Teacher,Student> one = new HashMap<Teacher,Student>();//Teacher,student都是自定义的类

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

Map<Teacher,ArrayList> one = new HashMap<Teacher,ArrayList>();
one.put(wang,wang.getStuList());
Teacher i = one.keySet().toArray(new Teacher[0])[0];
System.out.println(i.toString());

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 @驽马

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template