• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Bear Bibeault
  • Knute Snortum
  • Liutauras Vilda
Sheriffs:
  • Tim Cooke
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Ron McLeod
  • Ganesh Patekar
  • salvin francis
Bartenders:
  • Tim Holloway
  • Carey Brown
  • Stephan van Hulst

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

 
Greenhorn
Posts: 2
  • 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
  • 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...
 
Sheriff
Posts: 21557
100
Chrome Eclipse IDE Java Spring Ubuntu VI Editor Windows
  • 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:

 
She still doesn't approve of my superhero lifestyle. Or this shameless plug:
Programmatically Create PDF Using Free Spire.PDF with Java
https://coderanch.com/wiki/703735/Programmatically-Create-PDF-Free-Spire
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!