【问题标题】:Need help on simplify a list of strings在简化字符串列表方面需要帮助
【发布时间】:2014-01-10 12:45:20
【问题描述】:

谁能帮我简化这个字符串列表:

public class MyList {

    // New customers
    public static final String mNew1 = "email1";
    public static final String mNew2 = "email2";
    public static final String mNew3 = "email3";
    public static final String mNew4 = "email4";

    // Old customers
    public static final String mOld1 = "email1";
    public static final String mOld2 = "email2";
    public static final String mOld3 = "email3";
}

public class App extends Application {
    public static boolean mIsNew = false;
    public static boolean mIsOld = false;

Pattern emailPattern = Patterns.EMAIL_ADDRESS;
        Account[] accounts = AccountManager.get(context).getAccounts();
        for (Account account : accounts) {
            if (emailPattern.matcher(account.name).matches()) {
                String possibleEmail = account.name;
                if (MyList.mNew1.matches(possibleEmail) || MyList.mNew2.matches(possibleEmail) ||
                        MyList.mNew3.matches(possibleEmail) || MyList.mNew4.matches(possibleEmail)) {
                    mIsNew = true;
                }
                if (MyList.mOld1.matches(possibleEmail) || MyList.mOld2.matches(possibleEmail) || MyList.mOld3.matches(possibleEmail)) {
                    mIsOld = true;
                }
            }
        }

由于老客户的电子邮件将在不到一周的时间内超过 10.000 封,您能否建议我一种从 MyList 类中选择字符串并启用正确布尔值的简单方法?即如果 oneOfTheStringInThisList.matches(possibleEmail) mIsOld = true。

我对字符串列表不是很熟悉,抱歉我的菜鸟问题!谢谢!

【问题讨论】:

    标签: android string list


    【解决方案1】:

    你可以通过反射得到值:

    private void Something()
    {
        MyList list = new MyList();
        HashSet<String> oldMails = new HashSet<String>();
        HashSet<String> newMails = new HashSet<String>();
        try {
            GetAllMails(list, oldMails, newMails);
        } catch (IllegalAccessException e) {
            // TODO
        }
    
        boolean mIsOld = oldMails.contains("email4");
        boolean mIsNew = newMails.contains("email4");
    }
    
    private void GetAllMails(MyList list, HashSet<String> oldMails, HashSet<String> newMails) throws IllegalAccessException
    {
        Field[] allFields = MyList.class.getDeclaredFields();   
        for(Field f : allFields)
        {
            if (f.getName().startsWith("mNew"))
            {
                newMails.add(f.get(list).toString());
            }
            else if (f.getName().startsWith("mOld"))
            {
                oldMails.add(f.get(list).toString());
            }
        }
    }
    

    您应该将 HashSet 存储在内存中,因为反射性能不是很好。

    【讨论】:

    • 这样我必须添加电子邮件 2 次!有没有办法将所有邮件添加到某种列表中并在列表中进行一次检查?
    • 您的应用中真的有 10000 个电子邮件地址作为硬编码字符串吗?
    • 不得不稍微调整一下,但是是的......这正是我正在寻找的解决方案!谢谢老哥!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-30
    • 1970-01-01
    • 2019-08-17
    • 1970-01-01
    • 2018-05-24
    • 1970-01-01
    相关资源
    最近更新 更多