Guest User

Untitled

a guest
Mar 17th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.52 KB | None | 0 0
  1. import org.junit.Assert;
  2. import org.junit.Test;
  3. import org.junit.runner.JUnitCore;
  4. import org.junit.runner.Result;
  5. import org.junit.runner.notification.Failure;
  6.  
  7. import java.util.ArrayList;
  8. import java.util.List;
  9.  
  10. import static org.hamcrest.CoreMatchers.is;
  11.  
  12.  
  13. public class SolutionTests {
  14.  
  15. public static void main(String[] args) {
  16. Result result = JUnitCore.runClasses(SolutionTests.class);
  17. for (Failure failure : result.getFailures()) {
  18. System.out.println(failure.toString());
  19. }
  20. }
  21.  
  22. @Test
  23. public void testThatWeCanAddToMapAndRetrieveFromMap() {
  24. MyMap<Integer, Integer> myMap = new MyMap<>();
  25.  
  26. int value = 2;
  27. int key = 1;
  28. myMap.put(key, value);
  29.  
  30. Assert.assertThat(myMap.get(key), is(value));
  31.  
  32. }
  33.  
  34.  
  35. @Test
  36. public void testThatWeCanAddMultipleValuesAndRetrieveRightValueFromMap() {
  37. MyMap<Integer, Integer> myMap = new MyMap<>();
  38.  
  39. int[][] setupData = {{1, 2}, {4, 5}};
  40.  
  41. for (int[] pair : setupData) {
  42. Integer key = pair[0];
  43. Integer value = pair[1];
  44. myMap.put(key, value);
  45.  
  46. }
  47.  
  48. Assert.assertThat(myMap.get(1), is(2));
  49. Assert.assertThat(myMap.get(4), is(5));
  50.  
  51. }
  52.  
  53. @Test
  54. public void testThatWeUpdateAMapNewValueForExistingKey() {
  55. MyMap<Integer, Integer> myMap = new MyMap<>();
  56.  
  57. int[][] setupData = {{1, 2}, {1, 5}};
  58.  
  59. for (int[] pair : setupData) {
  60. Integer key = pair[0];
  61. Integer value = pair[1];
  62. myMap.put(key, value);
  63.  
  64. }
  65.  
  66. Assert.assertThat(myMap.get(1), is(6));
  67.  
  68. }
  69.  
  70. public class MyMap<K, V> {
  71.  
  72. private List<MyEntry<K, V>> myEntryList = new ArrayList<>();
  73.  
  74. public void put(K key, V value) {
  75. myEntryList.add(key.hashCode(), new MyEntry<>(key, value));
  76. }
  77.  
  78. public V get(K key) {
  79. return myEntryList.get(key.hashCode()).getValue();
  80. }
  81.  
  82. public class MyEntry<K, V> {
  83. private K key;
  84. private V value;
  85.  
  86. public MyEntry(K key, V value) {
  87. this.key = key;
  88. this.value = value;
  89. }
  90.  
  91. public K getKey() {
  92. return key;
  93. }
  94.  
  95. public V getValue() {
  96. return value;
  97. }
  98.  
  99. @Override
  100. public String toString() {
  101. return "MyEntry{" +
  102. "key=" + key +
  103. ", value=" + value +
  104. '}';
  105. }
  106. }
  107. }
Add Comment
Please, Sign In to add comment