【问题标题】:Access HashMap data from another class从另一个类访问 HashMap 数据
【发布时间】:2019-01-05 22:43:01
【问题描述】:

我有一个类,其中有一个填充的 HashMap 和 ArrayList。我需要在我的其他类中访问 HashMap 和 ArrayList 中的键和值,当我这样做时,程序返回 NULL?

我的 HashMap 在这个类中:

package championsLeagueTeamGenerator;

import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.Collections;

public class topTier extends GroupStages {

    public static ArrayList <Integer> x = new ArrayList <Integer>();
    public static HashMap <Integer, String> xx = new HashMap();


    public static void firstPot() {

        x.add(1);
        x.add(2);
        x.add(3);
        x.add(4);
        x.add(5);
        x.add(6);
        x.add(7);
        x.add(8);

        Collections.shuffle(x);

        xx.put(x.get(0), "Manchester United");
        xx.put(x.get(1), "Barcelona");
        xx.put(x.get(2), "Real Madrid");
        xx.put(x.get(3), "Paris St Germain");
        xx.put(x.get(4), "Bayern Munich");
        xx.put(x.get(5), "Juventus");
        xx.put(x.get(6), "Chelsea");
        xx.put(x.get(7), "Liverpool");

        System.out.println(xx);

 }

我想在这个类中访问它:

package championsLeagueTeamGenerator;

import java.util.HashMap;
import java.util.ArrayList;
import java.util.Collection;

public class GroupStages {

    public static ArrayList <String> groupA = new ArrayList<String>();

    public static void groupOne() {         
        System.out.print(topTier.xx.get(1));        
    }   
}

但是程序返回NULL,这是为什么呢?

【问题讨论】:

  • topTier 来自哪里?

标签: java arraylist data-structures hashmap


【解决方案1】:

您错过了在 topTier 类中执行 firstPot() 静态方法。

这将为您提供正确的输出。


public static void groupOne() {

    topTier.firstPot();
    System.out.print(topTier.xx.get(1));

   }

【讨论】:

  • topTier 未声明,也无法从 GroupStages 类访问
  • 谢谢@VaibhavSingh,它成功了。只是为了我自己的个人开发,是不是必须先声明方法才能使用。例如topTier.firstPot();.
猜你喜欢
  • 1970-01-01
  • 2015-10-20
  • 2012-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多