【问题标题】:How to check if List<BasicNameValuePair> contains a key?如何检查 List<BasicNameValuePair> 是否包含键?
【发布时间】:2014-08-13 00:10:29
【问题描述】:

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

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)

【问题讨论】:

  • 题外话:可以使用isEmpty()检查数组是否为空,优于size()(大小需要遍历整个列表)。
  • @AVolpe 感谢您的来信!从来没有想过在我的整个应用程序中可能有很多性能问题是因为这个!
  • 您不应该为此使用哈希表吗?
  • @RobertHarvey 因为这将用于 HttpPost,所以需要: public UrlEncodedFormEntity (List extends NameValuePair> parameters)
  • 或者哈希表可能是 NameValuePair 的基础...我真的不知道

标签: java android collections http-post basicnamevaluepair


【解决方案1】:

好像mPostPairs是一个List&lt;BasicNameValuePair&gt;,而且一个list不知道里面存放的是什么类型的对象,你可以遍历一下看看

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

【讨论】:

    猜你喜欢
    • 2022-01-09
    • 2013-03-14
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    • 1970-01-01
    • 1970-01-01
    • 2016-09-16
    • 1970-01-01
    相关资源
    最近更新 更多