File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Head first Java telling me to Change an Int Array to ArrayList - Eclipse telling me no can do Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Head first Java telling me to Change an Int Array to ArrayList - Eclipse telling me no can do" Watch "Head first Java telling me to Change an Int Array to ArrayList - Eclipse telling me no can do" New topic
Author

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

Seraph none
Greenhorn

Joined: Dec 13, 2010
Posts: 2
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

Joined: Dec 13, 2010
Posts: 2
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

Joined: Oct 27, 2005
Posts: 19720
    
  20

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:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
jQuery in Action, 2nd edition
 
subject: Head first Java telling me to Change an Int Array to ArrayList - Eclipse telling me no can do