Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Instead of having two lists just use a <code>Map&lt;String, List&lt;Station&gt;&gt;</code>. The <code>trainNumber</code> would be the unique key and you could easily add or delete stations from the corresponding list in the map.</p> <p><strong>UPDATE</strong></p> <p>As suggested by @ipavlic use <code>Map&lt;String, Set&lt;Station&gt;&gt;</code>, since a set allows no duplicate elements.</p> <p><strong>UPDATE2</strong></p> <p>Here a little example, with some comments. The example shows you just how to use a map combined with a set. You should <strong>not</strong> copy this into you code 1:1, since this is not a object-oriented approach. The map should be encapsulated in some object.</p> <pre><code>import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.TreeSet; public class MapSetExample { public static void main(String[] args) { Map&lt;String, Set&lt;String&gt;&gt; map = new HashMap&lt;String, Set&lt;String&gt;&gt;(); System.out.println("ADDED = " + add(map, "Train1", "Station1")); System.out.println("ADDED = " + add(map, "Train1", "Station2")); System.out.println("ADDED = " + add(map, "Train1", "Station1")); System.out.println("Stations of Train1 = " + map.get("Train1")); } private static boolean add(Map&lt;String, Set&lt;String&gt;&gt; map, String key, String station) { Set&lt;String&gt; set = map.get(key); /* If map.get() returns null, that means there is no set * in the map associated with given key. * * In that case we create a new set. * * If there is already a set, we use that one. */ if (set == null) { set = new TreeSet&lt;String&gt;(); map.put(key, set); } /* False if station is already in set. At this point you could also delete sth. etc. */ boolean success = set.add(station); return success; } } </code></pre> <p><strong>OUTPUT</strong></p> <pre><code>ADDED = true ADDED = true ADDED = false Stations of Train1 = [Station1, Station2] </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload