0

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);
6
  • How can you replace? HashMap is belong to Map while List is List. Commented Jul 9, 2014 at 6:26
  • 1
    stackoverflow.com/questions/2395814/… Commented Jul 9, 2014 at 6:27
  • kindly explain me the difference between list and Map @PhamTrung Commented Jul 9, 2014 at 6:27
  • 1
    @Nepster ha ha, just read the link I gave you in the comment :) Geek's link is also a good one. Commented Jul 9, 2014 at 6:31
  • how can i accept Geek Answer. Thanks to both PhamTrung and Geek Commented Jul 9, 2014 at 6:41

5 Answers 5

2

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, e.g. if your unfamiliar with Maps 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.

Sign up to request clarification or add additional context in comments.

3 Comments

when to choose which one.
that depends @Nepster how many values will be in ur list? many login username or password or just one?
It does not simply depend on the size of the list, but on the operation you want to execute on the data structure before you pass it to the UrlEncodedFormEntity constructor. If you need to access the data often then it's worth creating a Map and transform it right before constructor invocation to a list. Never underestimate power of the good old O(1) of a hash table.
1

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) ;)

Comments

1

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]);

3 Comments

NameValuePair does the same . See my Question . I am passing username and password
Right, however for retrieving password or username you will have to iterate over list and find out which NameValuePair matches "username" or password. This will be inefficient if list goes bigger.
@Nepster a map of string is not the same a list of pairs. In the map case, the value hold in the data structure is a string. It happens to be indexed by a string, but it's not always true. In the list case, the value hold in the data structure is the actual pair of two strings.
0

UrlEncodedFormEntity constructor accepts only 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

Comments

0

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> or 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); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.