I am studying a book by Bert Bates and Kati Sierras on Java.

When implementing a game (by the principle of sea battle) using the ArrayList class from the standard Java library (API), an error occurs:

The method setLocationCells (ArrayList) in the type of SimpleDotCom is not applicable for the arguments (int [])

The game itself looks like this:

public class SimpleDotComTestDrive { public static void main(String[] args) { //переменная для хранения количества ходов int numOfGuesses = 0; //специальный класс, который содержит метод для приема пользовательского ввода. GameHelper helper = new GameHelper(); SimpleDotCom theDotCom = new SimpleDotCom(); //генерируем случайное число для первой ячейки и используем его для формирования массива ячеек. int randomNum = (int) (Math.random() * 5); // Создаем массив для местоположения (три последовательности числа из семи) int[] locations = {randomNum, randomNum+1, randomNum+2}; //передаем местоположение ячеек(массив). theDotCom.setLocationCells(locations);//В этой строчке ошибка с вызовом сеттера setLocationCells //создаем булевую переменную, чтобы проверять в цикле, не закончилась ли игра boolean isAlive = true; while(isAlive == true) { //получаем строку вводимую пользователем String guess = helper.getUserInput("Введите число"); //проверить полученные данные: сохраняем возвращенный результат в переменную типа String String result = theDotCom.checkYourself(guess); //Инкрементируем количество попыток numOfGuesses++; //Если да, то присваиваем isAlive значение false (так как не хотим продолжать цикл) и выводим на экран количество попыток if (result.equals("Потопил")) { isAlive = false; System.out.println("Вам потребовалось " + numOfGuesses + " попыток(и)"); } } } } public class SimpleDotCom { private ArrayList<Integer> locationCells; public void setLocationCells(ArrayList<Integer> loc) { //сеттер locationCells = loc; } public String checkYourself(String stringGuess) { // Создаем переменную для хранения результата, который будем возвращять. // Присваиваем по умолчанию строковое значение "Мимо"(то есть подразумеваем // промах). String result = "Мимо"; //Проверяем содержится ли загаданная пользователем ячейка внутри ArrayList, запрашивая ее индекс. //Если ее нет в списке, то indexOf() возвращает -1. int index = locationCells.indexOf(stringGuess); //Если индекс больше или равен нулю, то загаданная пользователем ячейка определенно //находится в списке, поэтому удаляем ее. if (index >= 0) { locationCells.remove(index); //Если список пустой, значит, это было попадание if(locationCells.isEmpty()) { result = "Потопил"; } else { result = "Попал"; } } return result; } } public class GameHelper { public String getUserInput(String prompt) { String inputLine = null; System.out.print(prompt + " "); try { BufferedReader is = new BufferedReader(new InputStreamReader(System.in)); inputLine = is.readLine(); if (inputLine.length() == 0) return null; } catch (IOException e) { System.out.println("IOException:" + e); } return inputLine; } } 

    2 answers 2

    Replace your line in this way.

     theDotCom.setLocationCells(Arrays.asList(locations)); 

    Just remember that creating a collection in this way tightly binds it to the array itself. When you try to resize it, you get a problem. In other cases, the method is quite suitable for use. This does not seem very logical at first glance, because if we receive a collection, it is quite logical that we do not want to depend on its size. But in fact it allows you to avoid stupid transformations. After all, if you create an array, you are sure of its size. If so, then you should not be confused by the collection tied to the size of the array. If you do not know the number of elements, then you need to immediately create a collection and add elements to it already, and not to create an unnecessary array for anyone with a view to its further conversion.

        List<Integer> list = Arrays.asList(locations); 
      • 2
        If you need a full java.util.ArrayList, then List <Integer> list = new ArrayList <> (Arrays.asList (locations)); - Oleksiy Morenets