本文介绍了如何从另一个类或函数中使用HashMap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个工作代码示例。感谢@markspace为我提供。
这里的代码是一个hashmap并插入值。

Here is a working code example. Thanks to @markspace for providing me with it.The code here makes a hashmap and inserts values in it.

 public class RpgPersonExample
{
   public static void main( String[] args )
   {
      Map<String, RpgPerson> team = new HashMap<>();
      team.put( "Sgt. Mayhem", new RpgPerson( 100, 10, 0 ) );
      team.put( "Wizard", new RpgPerson( 100, 1, 10 ) );
      team.put( "Dragon", new RpgPerson( 1000, 100, 100 ) );

      System.out.println( team.get( "Dragon" ) );
      System.out.println( team.get( "Wizard" ) );
   }

}

class RpgPerson
{

   private int hits;
   private int strength;
   private int magic;

   public RpgPerson( int hits, int strength, int magic )
   {
      this.hits = hits;
      this.strength = strength;
      this.magic = magic;
   }

   @Override
   public String toString()
   {
      return "RpgPerson{" + "hits=" + hits + ", strength=" +
              strength + ", magic=" + magic + '}';
   }

}

从另一个类中使用它。如果我使用

What I want to do though is to use it from another class. If I use

       System.out.println( team.get( "Dragon" ) );

从主函数它工作正常。但是我该怎么做,我想从另一个类做呢?

from the main function it works fine. But how should I do i I want to do it from another class?

Public class Test {
     public static void example(){
         System.out.println( RpgPerson.team.get( "Dragon" ) );
     }
}

Test类明显不起作用,

The class Test does obviously not work but what should I do if I want it to work?

推荐答案

你可以做的最简单的事情是传入示例方法一个参数,引用 Map

The simplest thing you can do is pass into the example method an argument that references the Map:

 public static void example(Map<String, RpgPerson> team) {
     System.out.println(team.get("Dragon"));
 }

这篇关于如何从另一个类或函数中使用HashMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 09:25