diff --git a/src/main/java/core/basesyntax/Application.java b/src/main/java/core/basesyntax/Application.java new file mode 100644 index 000000000..2797a1e7b --- /dev/null +++ b/src/main/java/core/basesyntax/Application.java @@ -0,0 +1,18 @@ +package core.basesyntax; + +import core.basesyntax.impl.StorageImpl; + +public class Application { + public static void main(String[] args) { + Storage storage = new StorageImpl<>(); + storage.put(1, "Value1"); + storage.put(2, "Value2"); + storage.put(3, "Value3"); + + System.out.println("Get value by key 2: " + storage.get(2)); + System.out.println("Storage size: " + storage.size()); + + storage.put(1, "NewValue1"); + System.out.println("Get updated value by key 1: " + storage.get(1)); + } +} diff --git a/src/main/java/core/basesyntax/StorageImpl.java b/src/main/java/core/basesyntax/StorageImpl.java new file mode 100644 index 000000000..649938e7f --- /dev/null +++ b/src/main/java/core/basesyntax/StorageImpl.java @@ -0,0 +1,43 @@ +package core.basesyntax; + +public class StorageImpl implements Storage { + private static final int MAX_SIZE = 10; + private final K[] keys; + private final V[] values; + private int size; + + public StorageImpl() { + keys = (K[]) new Object[MAX_SIZE]; + values = (V[]) new Object[MAX_SIZE]; + } + + @Override + public void put(K key, V value) { + for (int i = 0; i < size; i++) { + if (key == null && keys[i] == null || key != null && key.equals(keys[i])) { + values[i] = value; + return; + } + } + if (size < MAX_SIZE) { + keys[size] = key; + values[size] = value; + size++; + } + } + + @Override + public V get(K key) { + for (int i = 0; i < size; i++) { + if (key == null && keys[i] == null || key != null && key.equals(keys[i])) { + return values[i]; + } + } + return null; + } + + @Override + public int size() { + return size; + } +} diff --git a/src/main/java/core/basesyntax/impl/StorageImpl.java b/src/main/java/core/basesyntax/impl/StorageImpl.java index 455a7b080..5c4d43eca 100644 --- a/src/main/java/core/basesyntax/impl/StorageImpl.java +++ b/src/main/java/core/basesyntax/impl/StorageImpl.java @@ -3,17 +3,44 @@ import core.basesyntax.Storage; public class StorageImpl implements Storage { + private static final int MAX_SIZE = 10; + private final K[] keys; + private final V[] values; + private int size; + + @SuppressWarnings("unchecked") + public StorageImpl() { + keys = (K[]) new Object[MAX_SIZE]; + values = (V[]) new Object[MAX_SIZE]; + } + @Override public void put(K key, V value) { + for (int i = 0; i < size; i++) { + if (key == keys[i] || (key != null && key.equals(keys[i]))) { + values[i] = value; + return; + } + } + if (size < MAX_SIZE) { + keys[size] = key; + values[size] = value; + size++; + } } @Override public V get(K key) { + for (int i = 0; i < size; i++) { + if (key == keys[i] || (key != null && key.equals(keys[i]))) { + return values[i]; + } + } return null; } @Override public int size() { - return -1; + return size; } }