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
Greg Kitchin
31,522 PointsLists vs Sets
So I'm rereading some notes for a Java exam next week, and I'm gotten to sets and lists, and I'm trying to see what advantage one has over the other. So far,
Lists are indexed, they can grow and shrink as needed, and they allow duplication.
Sets on the other hand, can also grow and shrink as needed, do not allow duplication, and are not indexed (any item has to be found by looping through it).
So I'm not seeing much that sets have over lists. Lists are easier to find the items required, allow duplication, and seem to offer far more control to the end user. Why would you use a set over a list? The only possible issue I can see is making sure duplication isn't possible, and even then, could probably be resolved with testing for conditions or such (for example, I wrote a tarot deck simulator program that would randomly generate 3 different numbers to represent each card, but duplication is possible. Using a set, I could get round that issue probably.)
1 Answer
Zuhayr Elahi
2,582 PointsHello. So this is really an interesting question. Although Lists are easier to implement and seem like they might be better, sometimes a Set is needed.
Lets start with an example. You have a table of ip address. e.g. (12.134.567.12, 45.134.23.56.78). Now IP addresses have to be unique. So you and I cannot be on the same network and have the same ip address. TO ensure that there are no duplicate ip addresses it would be better to store them in a Set. A Set allows us to ensure the user does not enter duplicates themselves.