中级农民
- 积分
- 166
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-5-27
- 最后登录
- 1970-1-1
|
你觉得这么写可以吗?
https://stackoverflow.com/questi ... sts-using-iterators
package com.example;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class IteratorMerge {
/**
* @param args
*/
public static void main(String[] args) {
List<String> list1 = Arrays.asList(new String[]{"A", "B", "C", "D"});
List<String> list2 = Arrays.asList(new String[]{"B", "D", "F", "G"});
System.out.println(merge(list1, list2));
}
public static List<String> merge(List<String> L1,List<String> L2) {
List<String> L3 = new ArrayList<String>();
Iterator<String> it1 = L1.iterator();
Iterator<String> it2 = L2.iterator();
String s1 = it1.hasNext() ? it1.next() : null;
String s2 = it2.hasNext() ? it2.next() : null;
while (s1 != null && s2 != null) {
if (s1.compareTo(s2) < 0) { // s1 comes before s2
L3.add(s1);
s1 = it1.hasNext() ? it1.next() : null;
}
else { // s1 and s2 are equal, or s2 comes before s1
L3.add(s2);
s2 = it2.hasNext() ? it2.next() : null;
}
}
// There is still at least one element from one of the lists which has not been added
if (s1 != null) {
L3.add(s1);
while (it1.hasNext()) {
L3.add(it1.next());
}
}
else if (s2 != null) {
L3.add(s2);
while (it2.hasNext()) {
L3.add(it2.next());
}
}
return L3;
}
}
补充内容 (2018-10-23 15:21):
啊,好像不对,这就不是iterator了,但可以不可以吧merge分成hasNext 和 next?
hasNext就是s1或s2还有继续,next就是return较小的那个数? |
|