基本情報技術者試験平成24年度春の問11です
import java.util.Comparator; public class ScoreManager extends ValueSortedMap< String, Integer > { private final String subject; public ScoreManager(String subject) { super(new Comparator<Integer>() { public int compare(Integer a, Integer b) { return b.compareTo(a); } }); this.subject = subject; } public void print() { System.out.println(subject + "の成績"); for (String name : this) { System.out.printf(" %s : %d点%n", name, name, get(name)); } } }
import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.noSuchElementException; import java.util.TreeMap; public class ValueSortedMap<K, V> implements Iterable<K> { Map<K, V> map = new HashMap<K, V>(); Map<V, List<K>> reverseMap; public ValueSortedMap() { reverseMap = new TreeMap<V, List<K>>(); } public ValueSortedMap(Comparator<? super V> c) { reverseMap = new TreeMap<V, List<K>>(c); } public V put(K key, V value) { if ( key == null || value == null ) { throw new NullPointerException(); } V old = remove(key); map.put(key, value); List<K> keys = reverseMap.get(value); if (keys == null ) { keys = new ArrayList<K>(); reverseMap.put(value, keys); } keys.add(key); return old; } public V get(K key) { return map.get(key); } public V remove(K key) { V value = (key); if ( value != null) { List<K> keys = reverseMap.get(value); keys.remove(key); if (keys.isEmpty()) { (value); } } return value; } public int size() { return map.size(); } public Iterator<K>() { return new Iterator<K>() { Iterator<V> vi = reverseMap.keySet().iterator(); Iteretor<K> ki = new ArrayList<K>().iterator(); public boolean hasNext() { return vi.hasNext() || ki.hasNext(); } public K next() { if (hasNext()) { if (!ki.hasNext()) { ki = reverseMap.get(vi.next()).iterator(); } return ki.next(); } throw new NoSuchElementException(); } public void remove() { throw new UnsupportedOperationException(); } }; } }
mainメソッド
public class ScoreManagerTester { public static void main(String[] args) { ScoreManager sm = new ScoreManager("数学"); try { sm.put("FE0001", 70); sm.put("FE0002", 90); sm.put("FE0003", 85); sm.put("FE0004", 95); sm.put("FE0005", 90); sm.put("FE0001", 85); sm.remove("FE0004"); sm.put(null, 90)j sm.put("FE0004", 90); } catch (NullPointerException e) {} sm.print(); System.out.println(sm.get("FE0004")); } }
質問内容
ValueSortedMapがmainメソッドから呼び出された際、最初にmapインスタンスが生成され、その後コンストラクタでreverseMapのインスタンスが生成されますよね?
その後のputメソッド内のV old = remove(key);がどのマップに適応されるのかわかりません。
このクラスの考え方、流れを教えて下さい
javaの勉強を始めたばかりで意味がわからないことを言っていると思うので、質問の意味がわからなかったらご指摘ください
申し訳ございませんがよろしくお願いします
回答2件
あなたの回答
tips
プレビュー