0

Our intents carry data from one activity to another by key value pairs called extras.

We initialize the key (i.e. declare it as a constant and assign it something e.g. public static final String mykey= "something";) before passing it to the intent by using intent.putExtra(mykey, myvalue);

My question is why do we need to assign a value to the key when it is being declared? What is the use of that value? What is the use of ' = "something" ' in public static final String mykey= "something";

I posted a related question, and a respected person (respected because of their valuable answers) said that when a final is declared, a value must be assigned so it is known what the constant is. Sounds like common sense.

But if I simply declare a constant public static final String a; the compiler does not complain at all, which means initializing a final variable with a value is not a must, as long as it is initialized before it is used.

A relevant answer is appreciated. Thank you in advance.

4

1 回答 1

1

我假设Intenta 由 a 支持Map

如果您将未初始化的变量作为键,这将意味着该值基本上丢失了:由于没有与之关联的键,因此无法检索它(尽管我相信可能根本不可能在其中插入null键一张地图)。

您不必实际将此键分配给变量:intent.putExtra("somekey", somevalue);也可以正常工作。

这只是确保您不会意外使用错误的密钥的问题。

作为说明为什么使用最终变量是有益的:

public static void main(String[] args) {
    Map<String, Integer> someMap = new HashMap<>();
    String theValue = "X";
    someMap.put(theValue, 5);
    System.out.println("Variable: " + theValue);
    System.out.println("Map: " + someMap.get(theValue));
    
    theValue = "Y";
    System.out.println("Variable: " + theValue);
    System.out.println("Map: " + someMap.get(theValue));
    System.out.println("ByValue: " + someMap.get("X"));
}

输出:

变量:X
地图:5

变量:Y
地图:null
ByValue:5

如果theValue是最终的,它将无法重新分配,并且从底层获取值不会有任何问题Map

于 2013-11-03T14:23:01.513 回答