• 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
  • Liutauras Vilda
  • Bear Bibeault
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • Devaka Cooray
Saloon Keepers:
  • Ganesh Patekar
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • salvin francis
Bartenders:
  • Ron McLeod
  • Frits Walraven
  • Pete Letkeman

Arraylist get problem  RSS feed

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
Im studying the book programming in BlueJ (Barnes/Kolling 5th ed.) and i am stuck at question 4.51.

I´ll try to explain:
There is an arraylist and I must get an object with a specific number, not an indexnumber, but a number which is one of the fields of the objects in the arraylist.

So the header of the method I am trying to write is:



but the number is an attribute of the objects (Lots) in the arraylist, not the indexnumber. I have no idea how to get the right Lot out of the arraylist. I only know how to access an object in an arraylist via its indexnumber. I hope you can help, I can provide more code from this project if neccesary.
thanks, Maarten.
 
Ranch Hand
Posts: 62
5
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

sonia jiem wrote:I have no idea how to get the right Lot out of the arraylist. I only know how to access an object in an arraylist via its indexnumber.


You have to iterate over the arraylist, using directly a for loop of using an Iterator (looping on the next()). For each object in the list you have to get that field and compare it with the requested value. Once found, you have the object and you can return it.
 
Ranch Hand
Posts: 449
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
write a for loop which examines each object in the list and returns the one with the right lotNumber, or null if isn't found.
@ps, Map is better structure for this.
 
Marshal
Posts: 4469
284
Clojure IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good advice so far. You do indeed need to iterate over the list and have a look inside each of your Lot objects.

But.

Muhammad Khojaye wrote:Map is better structure for this.


for the example you are describing is not necessarily true.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!