如何检查List <basicnamevaluepair>是否包含密钥?</basicnamevaluepair>

时间:2014-08-13 00:10:30

标签: java android collections http-post basicnamevaluepair

我有一个构建HttpResponse初始化程序的类。在其中一个应该返回BasicNameValuePair的方法中,我必须检查列表中是否有一个条目,其中包含由“name”指定的键或名称。

public List<BasicNameValuePair> getPostPairs() {
    if(mPostPairs == null || mPostPairs.size() < 1) {
        throw new NullPointerException(TAG + ": PostPairs is null or has no items in it!");
    }

    //there is no hasName() or hasKey() method :(
    if(!mPostPairs.hasName("action")) {
        throw new IllegalArgumentException(TAG + ": There is no 'action' defined in the collections");
    }

    return mPostPairs;
}

怎么做?如果使用BasicNameValuePair是不可能的,那么替代方案是什么?继承并添加方法?

我需要将它用于HttpPost,其setEntity只接受此类型:

public UrlEncodedFormEntity (List<? extends NameValuePair> parameters)

1 个答案:

答案 0 :(得分:2)

似乎mPostPairsList<BasicNameValuePair>,并且列表不知道存储了哪种对象,您可以迭代它并检查

boolean finded = false;
for (BasicNameValuePair pair : mPostPairs) {
    if (pair.getName().equals("action")) {
        finded = true;
        break;
    }
}
if (finded)
    return mPostPairs;
else
    throw new IllegalArgumentException(TAG + ": There is no 'action' defined in the collections");

或更短:

for (BasicNameValuePair pair : mPostPairs) 
    if (pair.getName().equals("action")) 
        return mPostPairs;
throw new IllegalArgumentException(TAG + ": There is no 'action' defined in the collections");
相关问题