简体   繁体   中英

Difference between HashMap<String,String> and List<NameValuePair>

While calling a loginTask i have to send username and password. Now i tried to replace this List<NameValuePair> code with HashMap<String,String> but i couldn't . Know i need to know the difference between them . when i should use List and when i should use HashMap

    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost(URL);

    List<NameValuePair> list = new ArrayList<NameValuePair>();

    list.add(new BasicNameValuePair("username", params[0]));

    list.add(new BasicNameValuePair("password", params[1]));

    httppost.setEntity(new UrlEncodedFormEntity(list));

    HttpResponse responce = httpclient.execute(httppost);

    HttpEntity httpEntity = responce.getEntity();

    response = EntityUtils.toString(httpEntity);

A HashMap (in Java an implementation of the java.util.Map interface and in theory referred to as hashtable) allows you access in O(1) while in a list of n pairs you have O(n) access time.

The choice which to use is both related to the use case (I left recommendations in my comment below because it refers to your very specific use case) and a tradeoff between different dimensions of software engineering, eg if your unfamiliar with Map s you might experience a maintenance overhead which stands in opposition to performance improvement (expressed as in O notation in this case). It's a decision.

The constructors of UrlEncodedFormEntity ( http://developer.android.com/reference/org/apache/http/client/entity/UrlEncodedFormEntity.html ) only accept List as parameter so the compiler will refuse to use a HashMap (of any kind)

Besides that, two Strings no not make a NameValuePair ( http://developer.android.com/reference/org/apache/http/NameValuePair.html ) ;)

HashMap is collection of key/value pair and one should use it when one wants to retrieve and insert values based on Key.

You can use it in this code like below,

Map<String, String> map = new HashMap<String, String>();
map.put("username",param[0]);
map.put("password",param[1]);

UrlEncodedFormEntity constructor accepts only List <? extends NameValuePair> List <? extends NameValuePair> not HashMap and to create result using format() ie following algorithm

public static String format (
            final List <? extends NameValuePair> parameters, 
            final String encoding) {
        final StringBuilder result = new StringBuilder();
        for (final NameValuePair parameter : parameters) {
            final String encodedName = encode(parameter.getName(), encoding);
            final String value = parameter.getValue();
            final String encodedValue = value != null ? encode(value, encoding) : "";
            if (result.length() > 0)
                result.append(PARAMETER_SEPARATOR);
            result.append(encodedName);
            result.append(NAME_VALUE_SEPARATOR);
            result.append(encodedValue);
        }
        return result.toString();
    }

Have a look on following link http://grepcode.com/file/repo1.maven.org/maven2/org.apache.httpcomponents/httpclient/4.0/org/apache/http/client/entity/UrlEncodedFormEntity.java

I'm adding my answer here because I can see there is some confusion among the other answers.

First of all, HashMap<K,V> is an implementation of the Map<K,V> interface, while the List<E> is just an interface, which needs to be implemented. ArrayList<E> is such an implementation.

A Map is used when you want to associate certain keys, with certain values. For example, it would make sense for a generic JSON parser to store the JSON object in a HashMap. A List, on the other hand, is used when you want to have an ordered collection of items.

Another thing I'd like to clear up, is that, contrary to what @KarlRichter mentions, an implementation of List , if done correctly, would access an element in O(1), and not in O(n). He seems to have confused the List with a LinkedList . A HashMap , would typically add the overhead of the hashing, so it could be just a little bit slower than List (in most cases unnoticeable), but still it would technically remain O(1).

However, a List serves a different purpose than a Map , so the comparison is still off the point.

In your case, you cannot replace List<NameValuePair> with HashMap<String,String> , because, as shown here , URLEncodedFormEntity only accepts List<? extends NameValuePair> List<? extends NameValuePair> or Iterable<? extends NameValuePair> Iterable<? extends NameValuePair> in all the available constructors.

If you must use a HashMap<String,String> , you could do some kind of conversion, like the following:

public List<NameValuePair> hashMapToNameValuePairList(HashMap<String,String> map) {

    List<NameValuePair> list = new ArrayList<NameValuePair>();

    for (Map.Entry<String, String> entry : map.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();
        list.add(new BasicNameValuePair(key, value));
    }

    return list;
}

So, then, you create your list from the HashMap like below:

List<NameValuePair> list = hashMapToNameValuePairList(yourHashMap); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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