java什么是键值,什么是键值对?

I am teaching myself Java so I can program android applications and came across the need to use a key value pair, but don't know what it is. I tried looking it up but cannot find any good resources to explain it.

Would anyone be able to explain this to me, or point me to a resource where I can read up on it?

Thanks!

edit: what I am confused about is how this is different from a normal variable. Say a variable of type String points to an object or int variable points to int value. Isn't that variable a "key", and the object a "value?

解决方案

At the simplest level, a key-value pair is just two values, one of which you have designated to be a "key" and the other you have designated to be the "value".

However, it is more common to talk about key-value pairs in the context of a mapping, i.e. a (mathematical) function which maps from a key to the corresponding value or values. Depending on the properties of this mapping, you may constrain the set of key-value pairs. For example, for a 1-to-1 mapping, you need the keys in the set to be unique.

Follow-up questions:

Is this the same as an array?

Well ... an array could be considered as a mapping from a set of indexes (integers) to values. But a mapping is more general. And in Java, arrays have other properties that distinguish them from Maps ... and they have a much simpler, faster, and less memory-hungry implementation.

(Note that in some languages, there is no "array" data type per-se. Instead, the primitive is a "hash" or an "associative array" ... which is a more general map.)

And is a key always a string?

No. A key can be any type. (It is generally a bad idea to use a mutable type as a key, especially if your mapping is implemented using one of the standard Map types in Java. However, even that can work in some circumstances.)

Say a variable of type String points to an object or int variable points to int value. Isn't that variable a "key", and the object a "value"?

No. Or at least, not in a static language like Java. The thing that distinguishes a key-value pair from a variable binding is that the "key" object is data, and hence can take different values. By contrast, a variable's name is hard-wired in the source code of your program: you can't change it at runtime.

(In some dynamic languages, you can create new variables dynamically (at runtime), and for such languages you could argue that variables are key-value pairs in a mapping that represents the scope ... at some point in the program's execution. But Java isn't like that ...)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值