psmith@mcwy.com wrote:> > I have two hashmaps, one called Students, which contains some results> The one I am having problems with is called results. I need to knowIt would make it simpler, if you reduced your problem to just the bit you are having the problem with. If you deleted students from your code, you wouldn't even need to explain that you don't have a problem with it.> how to iterate through an array to set the grade up as a key in the> hashmap. This is the element of code I am struggling with:> > public class TutorGroup> Map<Character, Set <String>> results; ^private final> public TutorGroup()> {> this.results = new HashMap<Character, Set<String>>();> }> > public void collateResults()> {> char grades[] = {'A', 'B', 'C', 'D', 'F', 'X'};> > for (int i = 0; i < grades.length; i++)> }> results.add(grades[i], " ");> }> > The value element of the results map will eventually hold the student> who has achieved the respective grade.So you are looking to add mappings to (initially) empty sets here?Rather than making "init" methods public, it's better to (effectively) add them to the constructor. Also an enum would be a better fit than char literals. So:enum Grade { A, B, C, D, F, X} public TutorGroup() { this.results = new java.util.EnumMap<Character, Set<String>>(Grade.class); for (Grade grade : Grade.values()) { this.results.put(grade, new java.util.HashSet<String>()); } }Unfortunately the Java library does not come with support for multimaps[1]. Writing a multimap yourself might be overkill, but you can factor out the initialisation code for arbitrary enums into a testable method: this.results = SomeOtherClas.createEnumMultimap(Grade.class);.... static <K extends Enum<K>,V> Map<T,Set<V>> createEnumMultimap( Class<K> keyType ) { Map<K,V> map = new java.util.EnumMap<K,V>(keyType); for (K key : keyType.getEnumConstants()) { map.put(key, new java.util.HashSet<V>()); } return map; }EnumMap is a very fast compact Map implementation.(Disclaimer: I haven't so much as attempted to compile any of this.)Tom Hawtin[1] http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4155149 (5 votes)
|