【发布时间】: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