java - Java中两个类共享静态变量

标签 java static treemap

我有两个类(class),地点类(class)和游戏类(class)。这不是继承关系,但我希望我的 Game 类有一个 Place 树状图,我的 Place 类也有一个树状图,但我希望这两个树状图是同一事物中的一个,这样我就不必不断更新两者。

出现的另一个问题是由于我需要做的事情的性质,每当我在构造函数中创建一个地点对象时,我需要立即使用places.put(id, this)将该对象放入树形图中,问题是构造函数要求我初始化树形图,但如果我每次调用构造函数时都初始化它,显然我每次都会得到新的 map 。

简而言之,我需要一种方法让两个类共享相同的静态 TreeMap ,并且 2. 只需初始化一次,这样我就不会重新初始化它。我正在考虑做一些时髦的事情,比如拥有一个 boolean isSet 数据成员,但我不想走那条路。

public Place(Scanner fileInput, Report rep) {
    // this constructor will only read enough information for one
    // place object and stop on the line for which place it read
    name = "";
    description = "";

    // report object contains fields to initialize to help
    // validate the data. // see report class
    int idNumber; 
    int linesToRead; // number of lines to read for one place object
    while ( (fileInput.hasNextLine() ) && rep.placeInfoFound() == false  ) {
    //1. Call getline. getline has a while loop that will continue
    // until it reaches a line of data worth reading
    // first data we expect is the places line
    // after that, we will be on the 'PLACES line which will have
    // two fields, both place and id.
    //2 call ListToTokens which will make an arraylist of words
    // where each element is a token. token sub 1 is the number of
    // places.

        ArrayList<String> tokens = new ArrayList<String>();
        tokens = findPlaceInfo(fileInput, rep);
    }
    places = new TreeMap<Integer, Place>();
    places.put(id, this);
    //WE HAVE TO REINITIALIZE the fact that we found
    // place info back to false so that when we call again
    // we can run the while loop
    rep.assert_place_info_found(false);
} // function brace

private static TreeMap<Integer, Place>places;

最佳答案

您希望使 map 成为 Place 类(或 Game 类,无论是哪个类)的静态成员,如下所示:

import java.util.Map;
import java.util.TreeMap;

public class Place {
    //  Static Attributes
    private static final Map<Place, Object> places = new TreeMap<>();

    //  Constructors
    public Place(final Object key, final Place value) {
        places.put(key, value);
    }

    //  Methods - Static Getters
    public static Map<Place, Object> getPlaces() { return places; }
}

因此,从“Game”类中,您可以静态调用 Place::getPlaces 函数。如果您尚未创建“Place”类,这将加载该类并实例化静态对象。然后,如果您愿意,可以缓存该引用。

话虽这么说,我建议不要将代码构造为依赖于这样的静态,因为紧密耦合可能会导致更复杂的代码到处跳转。不过,如果不更好地了解您的项目及其需求,我无法提出太多建议,所以我就到此为止。

祝你好运!

关于java - Java中两个类共享静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52601523/

相关文章:

java - TaxCore - 使用智能卡证书请求 token

java - 在servlet中从表(oracle)中获取数据并传递给jsp

java - 从独立客户端查找远程 EJB 时出现断言错误 "Context may not be null"

Java非空循环会影响线程读取静态变量吗?

java - TreeMap 中的空指针异常

java - 用于 eclipse juno 的 AngularJs 插件

java - 从另一个类测试泛型类的 main 方法

Swift 单例与静态属性/方法

java - 将 <Object, Object> 放入 TreeMap 时出错

java - Gwt NavigableSet 找不到源