简体   繁体   English

使用另一种方法的HashMap?

[英]Using a HashMap from another method?

If I had a HashMap such as in the following, how would I utilize it from another method? 如果我有如下所示的HashMap,如何从其他方法中利用它? In this case, from Main? 在这种情况下,来自Main?

public class Scratch {


public static void init() {
    WordEnums words = new WordEnums();

    List<String> bookList = new ArrayList<String>();
    for (WordEnums.Book bookValues : WordEnums.Book.values()) {
        bookList.add(bookValues.getDefinition());

    }


    HashMap<String, Object> wordDefinitions = new HashMap<>();
    wordDefinitions.put("book", bookList);


}


public static void main(String[] args) {
    List<String> book = (List<String>) wordDefinitions.get("book");

    book.stream().forEach(s -> {
        System.out.print("    ");
        System.out.println(s);
    });


}

I've tried moving it outside of init, something along the lines of what I could find here 我尝试将其移到init之外,这与我在此处可以找到的内容类似

But upon doing so, I get an error and am unable to access bookList within init. 但是这样做时,出现错误,无法在init中访问bookList。

Thanks 谢谢

You can either define it as a static or create get method and get it through instance of the class it's in. 您可以将其定义为静态方法,也可以创建get方法并通过其所在类的实例获取它。

Java static: https://www.javatpoint.com/static-keyword-in-java Java静态: https//www.javatpoint.com/static-keyword-in-java

Something to be aware of: 有一点要注意的:

When you declare a member of a class static , it isn't associated with any instance of the class that you create. 当您声明类的成员static ,它与您创建的类的任何实例都没有关联。 Given this information, you really have to think about how you want to structure your program. 有了这些信息,您实际上必须考虑如何构造程序。

If the method signature for init has to remain as you've written, you could make wordDefinitions a static member of your class and access it from init . 如果init的方法签名必须保持不变,则可以使wordDefinitions成为类的static成员,然后从init访问它。 However, if you do take this approach, be careful when you reference it. 但是,如果您确实采用这种方法,则在引用它时要小心。 Remember that there is only one instance of wordDefinitions . 请记住,只有wordDefinitions一个实例。 Thus, you can only access it through referencing your class ( Scratch ) and not an instance of it. 因此,您只能通过引用您的类( Scratch )而不是其实例来访问它。

The precise answer to the title question is "you can't". 标题问题的准确答案是“您不能”。 Here is why: 原因如下:

The variable named wordDefinitions does not exist outside of the init method. 名为wordDefinitions的变量在init方法之外不存在。 The scoping rules of Java say that it comes into existence every time you execute init and it no longer exists when init terminates. Java的作用域规则说,它在您每次执行init时就存在,而在init终止时不再存在。 Thus accessing it from outside init has no meaning. 因此,从外部init访问它没有任何意义。

Similarly for bookList , which is why when you move the declaration of wordDefinitions outside of init , you have no access to bookList . bookList类似,这就是为什么将wordDefinitions声明wordDefinitions init之外时,您无权访问bookList

You would probably benefit from a review of Java's scoping rules. 您可能会受益于Java范围规则的回顾。 But for now, here's an approximate guide. 但是现在,这是一个大概的指南。 For any data, you need to decide on its lifetime: 对于任何数据,您需要确定其寿命:

  1. One copy that 'always' exists independent of any instances of the class: declare it static in the class. “始终”存在的一个副本独立于类的任何实例:在类中将其声明为静态。

  2. A copy for each instance that exists for the lifetime of the instance: declare it non-static in the class (and perhaps initialize it in a constructor). 在实例生命周期中存在的每个实例的副本:在类中将其声明为非静态的(并可能在构造函数中对其进行初始化)。

  3. Data that only exists while a method is executing: declare it in the method body. 仅在方法执行时存在的数据:在方法主体中声明它。

Given the above, you can access data "upwards" in the list but not "downwards". 鉴于以上所述,您可以在列表中“向上”访问数据,但不能“向下”访问数据。

This glosses over the distinction between a variable and the object it refers to, but I'm trying to keep it simple. 这掩盖了变量和它所引用的对象之间的区别,但是我试图使其简单。

For your current problem, if you prefer to have all static methods (which seems to be something that introductory students do - are you taught that way? If so, I don't want to confuse matters by proposing differently) you should move the declaration of wordDefinitions to class scope with a static qualifier. 对于您当前的问题,如果您希望拥有所有静态方法(这似乎是入门学生要做的事情–您是否这样教过?如果这样,我不想通过提出不同的建议来混淆问题),则应移动声明使用静态限定符将wordDefinitions为类范围。 Loading in the book list can still be done in init . 仍然可以在init完成书列表中的加载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM