2013-12-21 52 views
0
列表

有人可以幫我simplfy字符串此列表:需要幫助的簡化串

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類中選擇字符串並啓用正確的布爾值? I.E如果oneOfTheStringInThisList.matches(possibleEmail)mIsOld = true。

我不是很熟悉字符串列表,很抱歉我的noob問題!謝謝!

回答

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()); 
     } 
    } 
} 

您應該HashSets存儲在內存中,因爲反射不是很高性能。

+0

用這種方式我必須添加電子郵件2次!沒有辦法在一個列表中添加所有的郵件並在列表中進行一次檢查嗎? – iGio90

+0

你的應用中是否真的有10000個電子郵件地址作爲硬編碼字符串? –

+0

沒有不是10.000,但500左右... :) – iGio90