简体   繁体   English

了解类的地图字段上的最终静态用法

[英]understanding a final static use on a map field of a class

I am c++ developer and trying to familiarize with Core Java concepts. 我是c ++开发人员,并试图熟悉Core Java概念。 i found this confusing as to my final static is something it cannot be changed after the object is constructed. 我发现这对于我的最终静态对象来说是一个令人困惑的问题,它在构造对象之后无法更改。 (correct me if i am wrong) (纠正我,如果我错了)

I came across the below implementation which i found confusing as it seems to allow value getting added into Map even when it is final static 我遇到了以下实现,我感到困惑,因为它似乎允许将值添加到Map中,即使它是最终静态的也是如此

public class MockUserServiceImpl implements UserService {

    private static final Map<String, User> userMap = new HashMap<String, User>();

    public static void addUserToCache(int userId, String userName) {
        if (!userMap.containsKey(userName)) {
            userMap.put(userName, new User(userId, userName));
        }
    } 
}

Can someone try to explain me what exactly the static final here is meant to 有人可以解释一下这里的static final到底是什么意思吗

Don't think of Map as a data structure. 不要将Map视为数据结构。 Think of it as any other class that has methods, for example put(..) . 可以将其视为具有方法的任何其他类,例如put(..) Are you saying that if you had 你是说如果你有

public class Foo {
    public void bar() {}
}

you shouldn't be able to call bar() on 你不应该能够调用bar()

final Foo foo = new Foo();

simply because it's final ? 仅仅因为它是final What use would it have then? 那会有什么用呢?

The final keyword only prevents a variable from being reassigned, not what methods can be called or what fields can be accessed. final关键字仅阻止重新分配变量,而不能调用什么方法或可以访问哪些字段。 It has a different meaning when used on on methods and classes. 在方法和类上使用时,它具有不同的含义。

As for static , read: 至于static ,请阅读:

What does the 'static' keyword do in a class? “ static”关键字在课程中做什么?

All objects in java are references. java中的所有对象都是引用。 final keyword means that the reference is final, but the object itself can be mutable. final关键字表示引用是最终的,但对象本身可以是可变的。 Look at Java's final vs. C++'s const . 看一下Java的最终版与C ++的const

Static keyword means that there is just single instance shared for all objects. 静态关键字表示所有对象共享一个实例。

static in Java in general means static context, something corresponding to classes. static在Java中,一般是指静态的情况下,对应的类的东西。 In this case static field can be seen a field of a class. 在这种情况下,可以将静态字段视为类的字段。 Static fields can also be seen as global variables. 静态字段也可以视为全局变量。

final is very similar to const in C++, meaning that the reference or value can not be re-assigned. final与C ++中的const非常相似,这意味着不能重新分配引用或值。

When used together they mean a constant reference or values having global visibility. 一起使用时,它们表示恒定的参考值或具有全局可见性的值。

You might also want to read JLS §8.3.1 Field Modifiers . 您可能还需要阅读JLS§8.3.1字段修饰符

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

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