• Post Reply Bookmark Topic Watch Topic
  • New Topic

Arraylist get problem  RSS feed

 
sonia jiem
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.
 
Andrea Binello
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.
 
Muhammad Khojaye
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.
 
Tim Cooke
Marshal
Posts: 4039
239
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.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!