1.在一些字符串數組中,常會有重復的記錄,比如手機號碼,我們可以通過Hashtable來對其進行過濾
public String[] checkArray(String[] str){
??? ??? Hashtable<String, String> hash=new Hashtable<String, String>();
??? ??? for(int i=0;i<str.length;i++){
??? ??? ??? if(!hash.containsKey(str[i]))
??? ??? ??? ??? hash.put(str[i], str[i]);
??? ??? }
??? ??? Enumeration enumeration=hash.keys();
??? ??? String[] str_new=new String[hash.size()];
??? ??? int i=0;
??? ??? while(enumeration.hasMoreElements()){
??? ??? ??? str_new[i]=enumeration.nextElement().toString();
??? ??? ??? i++;
??? ??? }
??? ??? return str_new;
??? }
示例:
??? ??? String[] mobile={"13811071500","13811071500","13811071501","13811071503","13811071501"};
??? ??? mobile=checkArray(mobile);
??? ??? for(int i=0;i<mobile.length;i++)
??? ??? ??? System.out.println(mobile[i]);
??? ?? 輸出結果為:
??? ??? 13811071503
??? ??? 13811071501
??? ??? 13811071500
2.A,B均為字符串數組,找出在A中存在,而在B中不存在的字符串
??? public String[] compareArray(String[] A,String[] B){
??? ??? Hashtable<String, String> hash=new Hashtable<String, String>();
??? ??? Hashtable<String, String> hash_new=new Hashtable<String, String>();
??? ??? for(int i=0;i<B.length;i++)
??? ??? ??? hash.put(B[i], B[i]);
??? ??? for(int i=0;i<A.length;i++){
??? ??? ??? if(!hash.containsKey(A[i]))
??? ??? ??? ??? hash_new.put(A[i], A[i]);
??? ??? }
??? ??? String[] C=new String[hash_new.size()];
??? ??? int i=0;
??? ??? Enumeration enumeration=hash_new.keys();
??? ??? while(enumeration.hasMoreElements()){
??? ??? ??? C[i]=enumeration.nextElement().toString();
??? ??? ??? i++;
??? ??? }
??? ??? return C;
??? }
示例:
??? ??? String[] mobile1={"13811071500","13811071501","13811071502","13811071503","13811071504"};
??? ??? String[] mobile2={"13811071500","13811071505","13811071502","13811071506","13811071504"};
??? ??? String[] mobile3=compareArray(mobile1,mobile2);
??? ??? for(int i=0;i<mobile3.length;i++)
??? ??? ??? System.out.println(mobile[i]);
輸出結果:
??? 13811071503
??? 13811071501
存在的問題:
每次都是倒序,可以再對程序稍加改動,變成正序。