与hamcrest罐子的Andr​​oid数组列表过滤器 [英] Android arraylist filter with hamcrest jar

查看:135
本文介绍了与hamcrest罐子的Andr​​oid数组列表过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Android项目,其中有一个自定义对象数组列表,现在我要筛选数组列表。但是,我总是得到零(新数组列表的大小)。

I have an android project, which have an custom object array list, now I want to filter that array list. But always I get zero (size of new array list).

public static <T> List<T> filter(Matcher<?> matcher, Iterable<T> iterable) {
    if (iterable == null)
        return new LinkedList<T>();
    else{
        List<T> collected = new LinkedList<T>();
        Iterator<T> iterator = iterable.iterator();
        if (iterator == null)
            return collected;
        while (iterator.hasNext()) {
            T item = iterator.next();
            if (matcher.matches(item))
                collected.add(item);
        }
        return collected;
    }
}

ArrayList<Products> sortedArrayList = (ArrayList<Products>) filter(Matchers.anyOf(
               Matchers.containsString(searchText),Matchers.containsString(searchText.toUpperCase())), productList);

为什么我得到零,请帮助。

Why I am getting zero, please help.

推荐答案

语句 matcher.matches(项目)在过滤方法总是返回,因为你有串的匹配( Matchers.containsString ),但项目的类型为产品(假设产品包含类型的项目产品)。

The statement matcher.matches(item) in the filter method returns always false because you have string matchers (Matchers.containsString) but item is of type Products (assuming that productList contains items of type Products).

Matchers.containsString 返回它继承形式 TypeSafeMatcher 并检查相匹配的价值有一个兼容的类型匹配。因此,它需要一个字符串却得到了一个产品对象。

Matchers.containsString returns a matcher which inherits form TypeSafeMatcher and checks that the matched value has a compatible type. So it expects a String but get a Products object.

我看到两个选项:


  • 更改 matcher.matches(项目) matcher.matches(item.getText()),其中的getText 提取相关的字符串匹配(你必须调整仿制药&LT; T&GT; - > &LT;吨产品扩展方式&gt;

  • 创建一个 FeatureMatcher

  • Change matcher.matches(item) to matcher.matches(item.getText()) where getText extracts the relevant string to match (you have to adjust the generics <T> -> <T extends Products>).
  • Create a FeatureMatcher

public class ProductsTextMatcher extends FeatureMatcher<Products, String> {

    public ProductsTextMatcher(Matcher<? super String> subMatcher) {
        super(subMatcher, "", "");
    }

    @Override
    protected String featureValueOf(Products actual) {
        return actual.getText();
    }

}

和调用它像这样:

filter(new ProductsTextMatcher(
        Matchers.anyOf(Matchers.containsString(searchText), Matchers.containsString(searchText.toUpperCase()))),
        productList); 


这篇关于与hamcrest罐子的Andr​​oid数组列表过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆