Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Christian Lawrence
3,941 PointsIs a Java ArrayList right to use here?
So I’m creating a text based game where you have various rooms to navigate through.
I want to have items in certain rooms that the user can find by typing ‘search’. If the room has an item (e.g. “diary”, ”apple“) it is placed into a collection. Am thing ArrayList called Items is the best for this?
Am also thinking I need a item class to store the Name, and Description of the item.
At certain stages, checks on the arrayList will need to be performed to see if it contains an item e.g. “apple”.
if (ArrayList Items contains apple){
pass
} else {
blocked
}
1 Answer
Ratul Sarna
Courses Plus Student 11,618 PointsHi,
ArrayList is a fine collection to use in this situation, since the number of items in a room will not be in thousands, I presume. If you are working with data in huge quantities, then, searching through it could become inefficient. But that does not seem to be the case here. Use the contains() method of the ArrayList class. Just implement an equals() method in your Item class.
On the other hand, you could use a HashSet instead of an ArrayList, if your room will not contain duplicate items. The contains() method in HashSet is really fast and efficient. It works in O(1) or constant time, ie. It does not have to go through the entire collection to look for an item. It knows where each item is. Check out its documentation here HashSet.
Christian Lawrence
3,941 PointsChristian Lawrence
3,941 PointsOk thank you this has been really helpful I will give both a try and get back to you.