I need to combine two list of strings in java, and I'm not sure if this is the best way to do this. I have to use iterators and compareTo () method. For instance...
Example: L1: A, B, C, D L2: B, D, F, G result: A, B, B, C, D, D, F, G
I can assume that the input lists are already sorted, and I cannot use the contains () method. I have some initial checks, but the while loop is what I'm stuck with.
public static ListADT<String> merge(ListADT<String> L1,ListADT<String> L2) throws BadListException { ListADT<String> L3 = new ArrayList<String>; if(L1 == null || L2 == null) { throw new BadListException(); } Iterator<String> itr1 = new L1.iterator(); Iterator<String> itr2 = new L2.iterator(); if(L1.size() == 0 && L2.size() == 0) { return L3; } if(L1.size() == 0 && L2.size() != 0) { for(int i = 0; i < L2.size(); i++) { return L3.add(L2.get(i)); } } if(L2.size() == 0 && L1.size() != 0) { for(int i = 0; i < L1.size(); i++) { return L3.add(L1.get(i)); } } while(itr1.hasNext() || irt2.hasNext()) {
}
Any help would be appreciated.
source share