I want to discuss a question about java collection framework. Here is the question:

You need to store elements in a collection that guarantees that no duplicates are stored. Which one of the following interfaces provide that capability?

a.java.util.List

b.java.util.Collection

c.java.util.Map

d.none of the above

It is pretty clear that the first two options are incorrect, but which one is true c. or d. and why? Personally, my answer is d.none of the above.

有帮助吗?

解决方案

Map does not allow duplicate keys of course but allows duplicate values. So I think the answer would be d). The collection that does not allow any duplicates is Set. An example with HashSet:

import java.util.HashSet;

public class Main {
  public static void main(String[] args) {
    HashSet<String> set = new HashSet<String>();
    set.add("str1");
    set.add("str2");
    set.add("str3");
    set.add("str4");
    set.add("str1");
    System.out.println(set); // ["str1", "str2", "str3". "str4"] "str1" is added only once
  }
}

其他提示

Interfaces provide no capabilities at all. So, d)

Set does not allow duplicates, Map will have unique key but can have duplicate values.

The answer should be C:

Take a look at the Map javadoc

An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.

so with something like this you can achieve the no duplicates requirement (Which is basically the implementation of HashSet):

String testString = "foo";
Map<String, String> map;
map.put(testString, testString);

A java.util.Map cannot contain duplicate keys.

Refer this Documetation

Get more details with example on this Example

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top