search

Home  >  Q&A  >  body text

java - hashmap如何获取键值?

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新手。

迷茫迷茫2767 days ago595

reply all(4)I'll reply

  • 高洛峰

    高洛峰2017-04-17 15:32:36

    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.

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 15:32:36

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

    toArray returns an array

    reply
    0
  • 阿神

    阿神2017-04-17 15:32:36

    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.

    reply
    0
  • 迷茫

    迷茫2017-04-17 15:32:36

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

    reply
    0
  • Cancelreply