aspose file tools*
The moose likes Beginning Java and the fly likes Search arraylist of objects Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Search arraylist of objects" Watch "Search arraylist of objects" New topic
Author

Search arraylist of objects

Brendan Cregan
Ranch Hand

Joined: Nov 11, 2011
Posts: 35
Hi All,

Im working on my arraylist library in particular im trying to implement a search method by title like this


Im just trying to search for the item first, but every time i do it doesn't appear in the console and im just returned to the menu.is there a better way to implement this?as my program is starting to be all over the shop!!
Thanks Again

Brendan


Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

You have a List<Book>. You're asking if that list contains a particular String.

Note that there is a difference between containing a Book with the title "X" and containing the String "X".

You can explicitly iterate and check each Book's title against the String the user provided. Or, you could construct a new Book with that titel, can call contains(), assuming that your Book's equals() method simply compares titles for equality.
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Also, this makes no sense:



The contains() method has no idea that you're iterating. It doesn't know about your index variable, or which book you're on. It simply iterates the list and returns true if it finds a match. If you want to know if a list contains something, you just call list.contains(that thing) exactly once. Yes it contains it, or no it doesn't.

With this code, if the list contains the book you're looking for, then you'll print "Found!" plus the book for every single book in the list, because that's what you're telling it do to.

>
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

And finally, that second block of cod is rather a lot for an SSCCE. (EDIT: Apparently the block I was referring to got edited out.) You've got a fair amount there that's not directly relevant to your question. For instance, the book/dvd/periodical repeated code. Even though it's not identical, it's so close, that either they all work or none do, so there's no reason to show them all; that's just clutter.
Brendan Cregan
Ranch Hand

Joined: Nov 11, 2011
Posts: 35
Hi Jeff,

I tried equals but its still acting a bit fishy...I have also been working on the inheritance of my program trying to create a LibraryItem List with all the library items, but by doing this i lose the classification of list that i have at the moment i.e. i have a list for books a list for dvds and a list for periodicals which makes it easy for me to list them all individually, but i was thinking if i was to store all these in libraryItems how could i tell them apart?

Thanks again for the help,

Brendan

Sorry Jeff but what code is the clutter?could you tell me the code lines?sorry just difficult for me to tell what part you are talking about
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Brendan Cregan wrote:Hi Jeff,

I tried equals but its still acting a bit fishy.


Then you did something wrong. :-) (Note that "doesn't work" is meaningless. Details about what was tried and exactly how it "didn't work" are needed.)

..I have also been working on the inheritance of my program trying to create a LibraryItem List with all the library items, but by doing this i lose the classification of list that i have at the moment i.e. i have a list for books a list for dvds and a list for periodicals which makes it easy for me to list them all individually, but i was thinking if i was to store all these in libraryItems how could i tell them apart?


If you use inheritance and polymorphism correctly, you don't need to tell them apart. All you care about is that each one IS-A LibraryItem, and each one will implement its version of the LibraryItem methods appropriate for its own type.

Sorry Jeff but what code is the clutter?could you tell me the code lines?sorry just difficult for me to tell what part you are talking about


Like I said: Anything that's not directly related to the problem you're having. And, to repeat the example I already gave, you have almost identical wads of code for "registering a dvd", "registering a book", etc. A proper SSCCE would have taken just one of those cases, in its own program (yes, that's more work for you, but it makes it easier for people to see where your problem is), with nothing else. Or, if the problem isn't directly about "registering" an item, then you would not show any of that stuff at all. Even if you have to start from scratch to produce a completely new (very small) program to demonstrate the problem.

Okay, so I might be overreacting a little. The basic principle holds though: The less code you show that's not directly related to the problem you're having, the easier it is for us to help you, and for you to understand our advice.
Brendan Cregan
Ranch Hand

Joined: Nov 11, 2011
Posts: 35
oh ok!sorry i just put in the code incase the error was outside the loop!
With regards the inheritance im adding books to a arraylist like this:

but this doesn't work anymore to return the list of books


getting this error
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.get(ArrayList.java:322)
at Library.main(Library.java:103)
and im pretty sure i know that this means theres nothing in book list.

and sorry if my codes convoluted, I'll work on it, it just helps me take it in a bit easier

Brendan
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Brendan Cregan wrote:oh ok!sorry i just put in the code incase the error was outside the loop!
With regards the inheritance im adding books to a arraylist like this:

but this doesn't work anymore to return the list of books


getting this error
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.get(ArrayList.java:322)
at Library.main(Library.java:103)
and im pretty sure i know that this means theres nothing in book list.


There is no way that that code can produce that error, unless you are using multiple threads and some other thread comes in after you call size() but before you finish iterating and shrinks the list (in which case you'd probably be getting a ConcurrentModificationException, but that's another story).

So either you're not running that code (e.g., you forgot to recompile after you changed something), or you're not looking closely enough at the file and line number the error message is complaining about.

What that exception tells us is that you're trying to access the first element (at index 0) of a list that is empty. That loop is totally legal, even on an empty list (the loop body will just never be entered), so your problem must be elsewhere, or you have the wrong version of the code.

Now, all that aside, it's a bad idea to iterate a List using get(i). Only use get(i) when you want to select a specific element by index. For iterating, you'll want to use an Iterator, usually under the syntactic sugar of a foreach loop. This form of iteration works for ALL Collections (unlike get(i) which only works for Lists), and should always provide O(n) iteration (unlike get(i) which provides O(n^2) on LinkedList).


Brendan Cregan
Ranch Hand

Joined: Nov 11, 2011
Posts: 35
thanks Jeff,

This is really frustrating(and your probably getting frustrated with my limited knowledge ;)), now when i add in your code
im getting no compiler errors but im not getting any list of books anymore...
does that code work with my arraylist?

im adding books into arraylist:

and printing them like you suggest


Thanks again
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Okay, I think you're getting lost in the weeds and trying to bite off too much at once.

Stop, step back, and start small.

Create a brand new program that does nothing but populate a simple List with hardcoded values and iterate over it, just using one of the two approaches.



Fill in an iterate/print loop. Try it first with the get(i) approach, then with the foreach approach. Even though you won't be using the get(i) approach in general, it will be a good introduction to see it in contrast to the foreach approach.

Once you get that working, try list.contains("a"), and list.contains("z").

Once you're comfortable with some basic manipulation of List<String>, try fiddling with a List<Book> or List<LibraryItem>, or add a couple member variables to that Test class and use a List<Test>. If, at any point as you're getting to more and more complex situations, you get lost in the weeds again, take a step back to a smaller incremental difference between what last worked (and that you understood) and where you're getting lost.

And of course, if you get stuck along the way in these baby steps, post another question.

I know this seems like you're going backwards and wasting time, but I promise you, it will end up saving you time, as well as a lot of frustration. Small steps, from something you understand to something just a little bit further up the learning curve.
Brendan Cregan
Ranch Hand

Joined: Nov 11, 2011
Posts: 35
thanks Jeff,

I will do this at some point but i have to keep hacking away at the library, its due in around 30 hours!!
I have a feeling im not too far off hacking my way to a somewhat complete system!

Brendan
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Brendan Cregan wrote:thanks Jeff,

I will do this at some point but i have to keep hacking away at the library, its due in around 30 hours!!
I have a feeling im not too far off hacking my way to a somewhat complete system!

Brendan


Your choice, of course. Note, however, that people will be more inclined to read and understand an SSCCE than your entire system, or some chunk of it you copy/paste here that will most likely be missing some context and on the other hand have a bunch of superfluous gunk. If your problem right now is with adding, iterating, printing, etc. a List, then the only kind of code I'm likely to look at now is of the kind I described above.

Good luck!

P.S. If you do it right and put just a bit of forethought into it, you can build on the SSCCE such that it will be easy to copy/paste from it into your code existing code, and you won't, in the end, have done much more work than you would have otherwise, in addition to which said work will be more productive. Heck, I've given you most of one SSCCE already. If you're having iterate/print problems, it should take you all of 15 minutes to provide your best-effort iterate/print code to my example, compile it, test it, and either understand it and move on or post a new question here about that piece of the problem.
Brendan Cregan
Ranch Hand

Joined: Nov 11, 2011
Posts: 35
Hi Jeff,

I really appreciate all the help that your giving me!just dont want to seem ungrateful I will revisit this issue!but im currently under a sea of dead lines!

im just working on one function at a time to try get as good a solution in the time i have left, i think my main problem is wrapping my head around accessing elements of an object in an arraylist...but i could be wrong!

the last hour i have been workinmg on it, particularly the Check out system!


I can see the problem myself, im trying to do too much in this line, or jumping to assumptions about the ease of accesing these elements in this line


the plan is to try sort this out, then create an array for each user and store books currently on loan in that array...think that would work?

Thanks

Brendan
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Brendan Cregan wrote:Hi Jeff,

I really appreciate all the help that your giving me!just dont want to seem ungrateful I will revisit this issue!but im currently under a sea of dead lines!


No problem. It doesn't matter to me either way. If your question is clear enough and I feel like helping, I will, and if not, I won't.

im just working on one function at a time


That's the way to do it. My previous exhortations about doing things piecemeal is all about that, with the additional advice to take the other stuff out of the picture as much as possible while tackling a given problem. If you're able to focus on one piece at a time, without interference from the other pieces, even when keeping your whole program intact, more power to you.


to try get as good a solution in the time i have left, i think my main problem is wrapping my head around accessing elements of an object in an arraylist...but i could be wrong!

I can see the problem myself, im trying to do too much in this line, or jumping to assumptions about the ease of accesing these elements in this line


You got lucky. This is one of those mistakes that's so common and so easy to spot than a full SSCCE is not generally necessary. Always use equals(), not ==, when comparing objects' states (including, for instance, Strings' contents).



Brendan Cregan
Ranch Hand

Joined: Nov 11, 2011
Posts: 35
that just dawned on me!think i have it now!


is this the correct way to approach the problem or is it a complete botch jobs?

Thanks

Brendan
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Brendan Cregan wrote:that just dawned on me!think i have it now!


is this the correct way to approach the problem or is it a complete botch jobs?

That looks like it should work. A few comments, however.

1. I assume that "bookList" is a list of books that are already checked out, and that if you don't find that book in that list, then it's not checked out, so it's available. If so, I would name that variable more descriptively, something like "checkedOutBooks." This will become especially important in situations where you have 2 or more lists that you're dealing with, and you need to distinguish "books which are checked out" from "books which are available" from "books which this user is currently requesting" from "books which are on hold".

2. I assume that EITHER you are setting curBook.available to true before starting the loop, so that the book is assumed to be available, and by the time you're done with the loop, it is indeed still marked as available only if it wasn't found in the list of checked-out books, OR curBook.available may already have been false (if some other user already checked it out), so that it's only available if it was BOTH not already unavailable AND not in the list of checked-out books.

3. It looks like you have two different ways to determine whether a book is available: its presence or absence on the list, and the value of its available field. This is fine if, for instance, the list is a temporary thing that's just used to collect a bunch of books that are going to become unavailable. If, however, you're using both indicators on an ongoing basis, then a) you're going to have to be very careful to keep them consistent with each other, and b) you're basically asking for confusion.

4. As I mentioned earlier, you should use a foreach loop to iterate, not get(i). If you're just sticking with get(i) because it's what you're comfortable with and you want to go on to solving other problems without worrying about learning more new stuff right now, that's fine. Just keep it in mind for the future.

5. This won't be a real issue for you here, but in general, when a single occurence in a collection is enough to determine that something exists, is unavailable, is good, is bad, whatever, we stop the iteration (usually with a break statement) as soon as we find that thing, to avoid wasting cycles iterating over the rest of the collection when it won't have any effect (e.g., in your case, once you set available to false, the rest of the iteration won't change it).
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39393
    
  28
Jeff Verdegan wrote:And finally, that second block of code . . .
What second block, Brendan Cregan? Have you changed a post after receiving a reply? That makes the respondent look bad. Don’t do it
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Campbell Ritchie wrote:
Jeff Verdegan wrote:And finally, that second block of code . . .
What second block, Brendan Cregan? Have you changed a post after receiving a reply? That makes the respondent look bad. Don’t do it


Heh. That's why I almost always quote what I'm commenting on--so that if the post gets edited, mine still makes sense. Oh, well, with any luck, he at least tried to digest my advice before editing. :-)
Brendan Cregan
Ranch Hand

Joined: Nov 11, 2011
Posts: 35
Hi,
Sorry i removed thee second main lump of code because Jeff said it wasnt helpful to just post all of the program, just the specific bits!have most of implementation done, can list all the things i need to (all items, all available items, all available books etc) and i can check in and out etc.just need to link the books loaned to a user and allow for editing of items...

Finally i think i see some light at the end of the tunnel ;)

Brendan
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Search arraylist of objects