A
A
Andrey Lyubimenko2019-06-09 09:35:58
Java
Andrey Lyubimenko, 2019-06-09 09:35:58

How to get an element from a collection when working with an iterator?

In the code, I marked where I want to call the next () method of the iterator, tell me how to handle it correctly - because it doesn’t work

package Lesson17_02_06.Home2;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

public class Runner {

  public static void main(String[] args) {
    
    //мой динамический массив
    List <Integer> list1 = new ArrayList<Integer>();
    
    //поток ввода
    InputStream input = null;
    Scanner sc = null;
    
    try {
      input = new FileInputStream("src/Lesson17_02_06/Home2/itClass.txt");
      sc = new Scanner(input);
      
      Iterator it = list1.iterator();
      
      while(sc.hasNext()) {
        Integer n = sc.nextInt();
        list1.add(n);
      }
      
      int countPositiv = 0;
      int countNegative = 0;
      while(it.hasNext()) {
        // КАК ОБРАТИТЬСЯ к следующему элементу коллекции ?
                                // метод it.next() - возвращает тип Object 
        if(n < 0) {
          countNegative++; 
        }else {
          countPositiv++;
        }
      }
      System.out.println("Кол-во отрицательных = " + countNegative + ", кол-во положительных = " + countPositiv );
      
    } catch (FileNotFoundException e) {
      System.out.println("Ошибка в файле!");
    } catch (IOException e) {
      e.printStackTrace();
    }
    input(list1);
  }
  
  public static void input(List <Integer> list1) {
    System.out.println(list1);
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2019-06-09
@andrewlybimenko

First, get a parameterized iterator, then it will not return Object
Second, you modify the collection after you have received an iterator for it, this will throw an exception ConcurrentModificationExceptionwhen you try to get an element from the iterator.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question