Session 12 |
Useful tips
Combine data structures
Sometimes it is useful to combine different data structures. For example, if we want to get to know which words follow the other words, we have to use a map whose keys are strings and their values are sets:
Map<String, Set<String>> wordSequences = new HashMap<>(); wordSequences.put("fish", new HashSet<>()); wordSequences.get("fish").add("swims"); wordSequences.get("fish").add("fingers");
Equals and Hashcode
Study the following code:
public class Client { private int clientNumber; public Client(int clientNumber) { this.clientNumber = clientNumber; } } public class Test { public static void main(String[] args) { Client myClient = new Client(123); Client theSameClient = new Client(123); List<Client> clients = Arrays.asList(myClient); System.out.println(clients.contains(theSameClient)); // false Integer clientNumber = new Integer(123); Integer theSameClientNumber = new Integer(123); List<Integer> clientNumber = Arrays.asList(clientNumber); System.out.println(clientNumber.contains(theSameClientNumber)); // true } }
Why does the line 13 return the false value, and the line 18 - true? Aren't they analogical examples? The issue will be explained during the Algorithms and Data Structure course in detail. At the moment, keep in mind that Java data structures cannot compare the content of objects; however, they can compare the primitive data types (including String
and generic data types).
Session 12 |