我试图将迭代器设为List<HashSet<Integer>> list = new ArrayList<>()
。
但是,我一直在跌倒。
这就是我尝试过的迭代器Iterator<HashSet<Integer>> iterator = new list.iterator()
请有人帮助我:(
如何创建该集合的迭代器?
这是代码的一部分
public class Test {
private static List<HashSet<Integer>> basketList = new ArrayList<>();
private static Map<Integer, Integer> map = new HashMap<>();
public static void settingBasket(String fname) throws FileNotFoundException {
Scanner scan = new Scanner(new File(fname));
int n = Integer.parseInt(scan.next());
Iterator<HashSet<Integer>> iter = basketList.iterator(); // error
for(int i=0; i<n; i++) {
scan.next();
int m = Integer.parseInt(scan.next());
HashSet<Integer> elems = new HashSet<>();
for(int j=0; j<m; j++)
elems.add(Integer.parseInt(scan.next()));
basketList.add(elems);
}
}
public static void settingPair() {
int size = basketList.size();
for(int i=0; i<size; i++) {
Iterator<HashSet<Integer>> iter = basketList.iterator(); // error
}
}
答案 0 :(得分:1)
您可以使用以下嵌套循环简单地遍历列表中的集合:
for (HashSet<Integer> set : basketList) {
for (Integer i : set) {
System.out.println(i);
}
}
或者,如果您希望列表中的每个Set都有一个Iterator,则可以按以下步骤进行操作:
for (int i = 0 ; i < basketList.size(); i++) {
Iterator<Integer> iter = basketList.get(i).iterator();
...
}
或:
for (HashSet<Integer> set : basketList) {
Iterator<Integer> iter = set.iterator();
...
}
答案 1 :(得分:1)
您可以试试吗?您可以使用HashSet<Integer> set1 = new HashSet<>(Arrays.asList(1, 2));
HashSet<Integer> set2 = new HashSet<>(Arrays.asList(3, 4));
List<HashSet<Integer>> list = new ArrayList<>(Arrays.asList(set1, set2));
// make iterator
Iterator<HashSet<Integer>> iterator = list.iterator();
while(iterator.hasNext()) {
// get element(HashSet) in iterator
HashSet<Integer> element = iterator.next();
for (Integer intValue : element) {
// access element in HashSet
System.out.println(intValue);
}
}
方法来简化它。
basketList
更新:您应该从
public static void settingPair() { int size = basketList.size(); for (int i = 0; i < size; i++) { // get the element from basketList HashSet<Integer> element = basketList.get(i); // create iterator Iterator<Integer> iterator = element.iterator(); } }
获取元素并创建一个迭代器。
像这样:
container:
image: maven:latest
build_task:
build_script: mvn clean compile test sonar:sonar
on_failure:
mail_script: mvn postman:send-mail