Are there "tagged" collections in Java? To clarify, I want to essentially classify each element in the list with some sort of Object (e.g. a String) so I can reference different objects in the开发者_Python百科 list by a tag that I specify, not by Object type or element contents.
EDIT: A HashMap will not work as the order of the items in the list is also deemed to be important. My understanding is that a HashMap is not practical when the order of the list matters in some way. If I am incorrect on this matter, by all means please correct me.
You're looking for a Map
. This data structure maps keys to values.
if each key in a Map maps to a Set of objects, you'll be able to easily look up every object with a particular tag(key)
No, as far as I know there are no "tagged" collections in the standard Java libraries. But you could use a Map<Tag,Set<String>>
to tag strings.
You could use a map
Map<String, Object> = new HashMap<String, Object>();
You can replace String with whatever you want. The one problem you might run into though, is if you want to categorize multiple objects with the same "tag". For instance, a "Cat" tag might apply to multiple, unique cat objects and a hashMap would only let you have one Cat object pointed to by the "Cat" tag. If that's what you want to do (multiple objects pointed to by one tag), you will need to declare the map as:
Map<String, List<Object>> = new HashMap<String, List<Object>>();
That will create a HashMap holding a list for each object so you can have multiple objects pointed to by one tag.
If you're not restricted to what's in the JDK, consider use of Guava Multimaps. They provide pre-built support for a map of sets.
If order is important then use a LinkedHashMap.
Perhaps a Map
is what you need
This is not detailed enough. We don't know if: - multiple tags per item are allowed - multiple items per tag are allowed
I'm going to go for the widest solution, where both of these are true. First thing you need is your Tag class (I suggest an enum)
public enum Tag {
TAG1, TAG2, TAG3; // add your tags here
}
Then your collection will be a Map where the key is your object, and the value your list of tags for each object.
Map<Object, List<Tag>> items = new HashMap<Object, List<Tag>>();
Of course, you can replace "Tag" with a String, if you want to allow any tag and not just known tags.
And depending what you want to do with your collection, you may want to reverse it:
Map<Tag, List<Object>> = new HashMap<Tag, List<Object>>();
I suggest first writing your test cases (unit-tests) listing your specifications, and the design of your collection will appear organically from them (TDD).
See SortedMap and TreeMap.
sounds like you want a hashmap
精彩评论