File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Head first Java telling me to Change an Int Array to ArrayList - Eclipse telling me no can do

 
Seraph none
Greenhorn
Posts: 2
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Im learning Java with Head First Java (had to buy it for my school, I actually think its a crap book)

And on page 139 it gives you the code for a Battleship type game. It uses two three classes, two of which I will put down here.

I think the problem is the code tells java to change a int array to an ArrayList. Which Eclipse tells me is impossible. But thats how the code in the Book is. My head hurts ;(

Heres the Code:


And the other class:


Ideas on how I can get it to work/ what i did wrong?
 
Seraph none
Greenhorn
Posts: 2
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I managed to solve the problem on my own by changing the locations int[] to a ArrayList! heres the result:


You can still comment on whether there is a better way or if this is fine...
 
Rob Spoor
Sheriff
Pie
Posts: 20396
47
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You must also change the calling code. Since the method now requires an ArrayList<String> you should provide an ArrayList<String>. So instead of you must use an ArrayList<String>:
I have two improvements though.

1) use ArrayList<Integer> instead of ArrayList<String>. You require numbers, not just any String. Make sure to validate the input.
2) program against interfaces. Instead of ArrayList you use List, except possibly for the initialization.

You can now use the following code:
That one "odd" line, Arrays.asList(randomNum, randomNum + 1, randomNum + 2), uses varargs. In this case, it requires Objects, so the ints are autoboxed into Integers. The result is a List<Integer>.

Hmmm, wait a second. Arrays.asList has one drawback - you cannot add to or remove from this List. You can solve this by copying the contents into an ArrayList:

 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic