String cannot be converted to ArrayList<String> Error

Here is a program similar to the sinking battleship game from the book head first java. After compiling I am getting the error: "String cannot be converted to ArrayList Error" and ^ pointer point to the line I have two different files one with the main method and other a separate class. Whats wrong here.

Main method class

import java.util.Scanner;
public class SimpleDotComTestDrive{

   public static void main(String[] args){

      SimpleDotCom dot=new SimpleDotCom();
      boolean repeat=false;
      String[] locations={"2","3","4"};
      dot.setLocationCells(locations);   //^ where compiler points the error
      Scanner input=new Scanner(System.in);
      System.out.println("Lets Start");

      while(repeat==false) {
         System.out.println("Type your guess");
         String userGuess=input.nextLine();
         String result=dot.checkYourSelf(userGuess);
         System.out.println(result);

         if(result=="kill") {
            repeat=true;
            break;
         }
      }
   } //close main
} //close test class

Separately saved class which is part of this program:

import java.util.ArrayList;

public class SimpleDotCom {
   private ArrayList<String>locationCells;

   public void setLocationCells(ArrayList<String> locs) {
      locationCells=locs;
   }

   public String checkYourSelf(String userGuess) {
      String result="miss";
      int index = locationCells.indexOf(userGuess);
      if(index>=0) { 
         locationCells.remove(index);

         if(locationCells.isEmpty()) {
            result="kill";
         }
         else {
            result="hit";
         }
    }
    return result;
  } //close check yourself method
} //close simple class

Answers


You are getting the error because setLocationCells() method accepts an ArrayList<String> and you are passing it a String Array by doing:

dot.setLocationCells(locations);

You should either replace your method to accept String[] instead of ArrayList<String> or change your code as follows:

dot.setLocationCells(new ArrayList<String>(Arrays.asList(locations));

You cannot have String[] locations={"2","3","4"}; and then parse it to the method setLocationCells(ArrayList<String> locs){ that requires the ArrayList.

So, there are more ways:

  1. Convert the array to list with: new ArrayList<String>(Arrays.asList(locations);
  2. Define the ArrayList instead:

    ArrayList<String> list = new ArrayList<String>() {{
        add("2");
        add("3");
        add("4");
    }};
    
  3. Change your method at all:

    public void setLocationCells(String[] locs){
        Collections.addAll(locationcells, locs);
    }
    

Need Your Help

LightSwitch WebApplication not entering Global.asax file

c# asp.net .net global-asax visual-studio-lightswitch

How can i get my lightswitch application to enter the global.asax file?

'6/1/2012' < '6/1/2012 0:00:00.000' = true?

sql sql-server

When I run this code in SQL-Server 2008,