diff --git a/.gitignore b/.gitignore
index 21b4487fb..7d6943e28 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,2 +1,3 @@
# Project exclude paths
-/out/
\ No newline at end of file
+/out/
+/resource/
diff --git a/src/com/walking/lesson37_collection_list/task1/Main.java b/src/com/walking/lesson37_collection_list/task1/Main.java
index 4753b4e8f..7fbf05b78 100644
--- a/src/com/walking/lesson37_collection_list/task1/Main.java
+++ b/src/com/walking/lesson37_collection_list/task1/Main.java
@@ -1,5 +1,12 @@
package com.walking.lesson37_collection_list.task1;
+import com.walking.lesson37_collection_list.task1.model.Counter;
+import com.walking.lesson37_collection_list.task1.service.CounterService;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.StringJoiner;
+
/**
* Реализуйте задачу
* ..., используя ArrayList.
@@ -10,6 +17,87 @@
* Изменилось ли что-то в кодовой базе при использовании списка другой реализации?
*/
public class Main {
+ public static final String GAS_COUNTER_NAME = "Газ";
+ public static final String HOT_WATER_COUNTER_NAME = "Горячая вода";
+ public static final String COLD_WATER_COUNTER_NAME = "Холодная вода";
+ public static final String ELECTRIC_COUNTER_NAME = "Электричество";
+
+ public static final String M_3_UNIT = "м3";
+ public static final String KW_H_UNIT = "кВт*ч";
+
+ private static final String LINE_DELIMITER = "-".repeat(20);
+
public static void main(String[] args) {
+ CounterService counterService = new CounterService(new ArrayList<>());
+ printOverview(counterService.getAllCounters());
+
+ Counter gasCounter = new Counter(GAS_COUNTER_NAME, M_3_UNIT);
+ Counter hotWaterCounter = new Counter(HOT_WATER_COUNTER_NAME, M_3_UNIT);
+ Counter coldWaterCounter = new Counter(COLD_WATER_COUNTER_NAME, M_3_UNIT);
+
+ Counter electricCounter = new Counter(ELECTRIC_COUNTER_NAME, KW_H_UNIT);
+ electricCounter.setValue(15);
+
+ counterService = new CounterService(List.of(coldWaterCounter, gasCounter));
+
+ counterService.addCounter(hotWaterCounter);
+ counterService.addCountersIfAbsent(electricCounter);
+ counterService.addCountersIfAbsent(electricCounter);
+ counterService.addCounter(electricCounter);
+ counterService.addFirst(electricCounter);
+ counterService.addFirst(new Counter("Электричество", KW_H_UNIT, 456));
+ counterService.increaseCounter(GAS_COUNTER_NAME, 100);
+ counterService.increaseCounter(coldWaterCounter, 10);
+ printOverview(counterService.getAllCounters());
+
+ counterService.removeDuplicates();
+ counterService.sortByName();
+ counterService.removeIdleCounters();
+ System.out.println(">>>Удаляем дубликаты, счетчики с нулевыми показаниями и сортируем по алфавиту:");
+ printOverview(counterService.getAllCounters());
+
+
+ System.out.println("Название первого в списке счетчика: " + counterService.getFirst().getName());
+
+ Counter[] allCounters = counterService.getAllCounters().toArray(new Counter[0]);
+ System.out.println(">>>Переносим счетчики из списка в массив и выводим их названия:");
+ printCounterNames(allCounters);
+
+ List waterCounters = List.of(hotWaterCounter, coldWaterCounter);
+
+
+ hotWaterCounter.setValue(100);
+ counterService.addCounter(hotWaterCounter);
+ counterService.removeIfNotMatch(waterCounters);
+ System.out.println(">>>Оставляем только счетчики воды:");
+ printOverview(counterService.getAllCounters());
+ }
+
+ public static void printCounterNames(Counter[] counters) {
+ StringJoiner result = new StringJoiner("\n", LINE_DELIMITER + "\n", "\n" + LINE_DELIMITER);
+
+ for (Counter counter : counters) {
+ result.add(counter == null ? "-" : counter.getName());
+ }
+
+ System.out.println(result);
+ }
+
+ public static void printOverview(List counters) {
+ System.out.printf("Всего счетчиков: %s\n%s\n", counters.size(), LINE_DELIMITER);
+
+ if (counters.isEmpty()) {
+ System.out.println("Добавьте счетчики для работы с ними.");
+ } else {
+ printCounterValues(counters);
+ }
+
+ System.out.println(LINE_DELIMITER);
+ }
+
+ private static void printCounterValues(List counters) {
+ for (Counter counter : counters) {
+ System.out.printf("%s: %d %s\n", counter.getName(), counter.getValue(), counter.getUnitOfMeasure());
+ }
}
-}
+}
\ No newline at end of file
diff --git a/src/com/walking/lesson37_collection_list/task1/model/Counter.java b/src/com/walking/lesson37_collection_list/task1/model/Counter.java
new file mode 100644
index 000000000..4ec88bde0
--- /dev/null
+++ b/src/com/walking/lesson37_collection_list/task1/model/Counter.java
@@ -0,0 +1,58 @@
+package com.walking.lesson37_collection_list.task1.model;
+
+import java.util.Objects;
+
+public class Counter implements Comparable {
+ private final String name;
+ private final String unitOfMeasure;
+
+ private int value;
+
+ public Counter(String name, String unitOfMeasure, int value) {
+ this.name = name;
+ this.unitOfMeasure = unitOfMeasure;
+ this.value = value;
+ }
+
+ public Counter(String name, String unitOfMeasure) {
+ this(name, unitOfMeasure, 0);
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getUnitOfMeasure() {
+ return unitOfMeasure;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ public void setValue(int value) {
+ this.value = value;
+ }
+
+ @Override
+ public int compareTo(Counter counter) {
+ return name.compareTo(counter.getName());
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ Counter counter = (Counter) o;
+ return Objects.equals(name, counter.name);
+ }
+
+ @Override
+ public int hashCode() {
+ return name.hashCode();
+ }
+}
\ No newline at end of file
diff --git a/src/com/walking/lesson37_collection_list/task1/service/CounterService.java b/src/com/walking/lesson37_collection_list/task1/service/CounterService.java
new file mode 100644
index 000000000..758b10776
--- /dev/null
+++ b/src/com/walking/lesson37_collection_list/task1/service/CounterService.java
@@ -0,0 +1,167 @@
+package com.walking.lesson37_collection_list.task1.service;
+
+import com.walking.lesson37_collection_list.task1.model.Counter;
+
+import java.util.*;
+
+public class CounterService {
+ /*// замена ArrayList на Vector не повлияла на кодовую базу, т.к. они оба реализуют интерфейс List,
+ // что делает их взаимозаменяемыми
+ private final Vector counters;
+
+ public CounterService(Counter... counters) {
+ this.counters = new Vector<>(Arrays.asList(counters));
+ } */
+
+ private final ArrayList counters;
+
+ public CounterService(List counters) {
+ this.counters = new ArrayList<>(counters);
+ }
+
+ public List getAllCounters() {
+ return List.copyOf(counters);
+ }
+
+ public Counter getFirst() {
+ return counters.get(0);
+ }
+
+ public void addFirst(Counter counter) {
+ counters.add(0, counter);
+ }
+
+ public Counter addCounter(Counter counter) {
+ counters.add(counter);
+ return counters.get(counters.size() - 1);
+ }
+
+ public boolean addCountersIfAbsent(Counter... counters) {
+ List candidates = new ArrayList<>(Arrays.asList(counters));
+ candidates.removeAll(this.counters);
+ return this.counters.addAll(candidates);
+ }
+
+ public boolean removeIfNotMatch(Collection extends Counter> sample) {
+ return counters.retainAll(sample);
+ }
+
+ public boolean removeDuplicates() {
+ List uniques = getUniques();
+
+ if (uniques.size() == counters.size()) {
+ return false;
+ }
+
+ counters.clear();
+ counters.addAll(uniques);
+ return true;
+ }
+
+ public boolean removeIdleCounters() {
+ List idles = getIdles();
+
+ if (idles.size() == 0) {
+ return false;
+ }
+
+ counters.removeAll(idles);
+ return true;
+ }
+
+ public void sortByName() {
+ counters.sort(Comparator.naturalOrder());
+ }
+
+ public void sortBy(Comparator comparator) {
+ counters.sort(comparator);
+ }
+
+ public Counter getCounterByName(String name) {
+ for (Counter counter : counters) {
+ if (counter.getName().equals(name)) {
+ return counter;
+ }
+ }
+
+ return null;
+ }
+
+ public Counter increaseCounter(String name, int value) {
+ Counter counter = getCounterByName(name);
+ return counter == null ? null : increaseCounter(counter, value);
+ }
+
+ public Counter increaseCounter(Counter counter, int value) {
+ counter.setValue(counter.getValue() + value);
+ return counter;
+ }
+
+ public Counter decreaseCounter(String name, int value) {
+ Counter counter = getCounterByName(name);
+ return counter == null ? null : decreaseCounter(counter, value);
+ }
+
+ public Counter decreaseCounter(Counter counter, int value) {
+ counter.setValue(counter.getValue() - value);
+ return counter;
+ }
+
+ public Counter incrementCounter(String name) {
+ Counter counter = getCounterByName(name);
+ return counter == null ? null : incrementCounter(counter);
+ }
+
+ public Counter incrementCounter(Counter counter) {
+ increaseCounter(counter, 1);
+ return counter;
+ }
+
+ public Counter decrementCounter(String name) {
+ Counter counter = getCounterByName(name);
+ return counter == null ? null : decrementCounter(counter);
+ }
+
+ public Counter decrementCounter(Counter counter) {
+ decreaseCounter(counter, 1);
+ return counter;
+ }
+
+ public Counter reset(String name) {
+ Counter counter = getCounterByName(name);
+ return counter == null ? null : reset(counter);
+ }
+
+ public Counter reset(Counter counter) {
+ counter.setValue(0);
+ return counter;
+ }
+
+ private List getUniques() {
+ List uniques = new ArrayList<>();
+
+ for (Counter counter : counters) {
+ if (!uniques.contains(counter)) {
+ uniques.add(counter);
+ }
+ }
+
+ return uniques;
+ }
+
+ private List getIdles() {
+ List idles = new ArrayList<>();
+
+ for (Counter counter : counters) {
+ if (isIdle(counter)) {
+ idles.add(counter);
+ }
+ }
+
+ return idles;
+ }
+
+ private boolean isIdle(Counter counter) {
+ return counter.getValue() == 0;
+ }
+}
\ No newline at end of file
diff --git a/src/com/walking/lesson37_collection_list/task2/Main.java b/src/com/walking/lesson37_collection_list/task2/Main.java
index 51a4575bb..f7339c5ed 100644
--- a/src/com/walking/lesson37_collection_list/task2/Main.java
+++ b/src/com/walking/lesson37_collection_list/task2/Main.java
@@ -1,5 +1,10 @@
package com.walking.lesson37_collection_list.task2;
+import com.walking.lesson37_collection_list.task2.structure.Stack;
+
+import java.util.ArrayList;
+import java.util.List;
+
/**
* Попробуйте реализовать собственную коллекцию, наследуясь от Collection.
* За основу можно взять
@@ -10,5 +15,53 @@
*/
public class Main {
public static void main(String[] args) {
+ Stack integers = new Stack<>();
+ integers.add(1);
+ integers.add(2);
+ integers.add(1);
+ integers.add(2);
+ integers.add(1);
+ integers.add(2);
+ System.out.println("Добавление элементов:\n" + integers);
+
+ int one = 1;
+ integers.remove(one);
+ integers.remove(1);
+ integers.remove(Integer.valueOf(1));
+ System.out.println("Удаление элементов:\n" + integers);
+
+ List integers12 = new ArrayList<>(List.of(1, 2));
+ System.out.println("Содержит все элементы из integers12? " + integers.containsAll(integers12));
+
+ integers.add(1);
+ integers.add(1);
+ integers.add(1);
+ System.out.println("Повторное добавление элементов:\n" + integers);
+
+ System.out.println("Содержит все элементы из integers12? " + integers.containsAll(integers12));
+
+ integers.clear();
+ System.out.println("Очистка:\n" + integers);
+
+ integers.addAll(List.of(1, 2, 3, 2, 1));
+ System.out.println("Добавление всех элементов другой коллекции:\n" + integers);
+
+ integers.removeAll(integers12);
+ System.out.println("Удаление всех элементов другой коллекции:\n" + integers);
+
+ integers.retainAll(integers12);
+ System.out.println("Удаление всех элементов отсутствующих в другой коллекции:\n" + integers);
+
+ Object[] objectsArray = integers.toArray();
+ Integer integer = (Integer) objectsArray[0];
+ Integer[] integersArray = integers.toArray(new Integer[0]);
+ Integer integer1 = integersArray[0];
+ Number[] numbersArray = integers.toArray(new Number[0]);
+ Number number = numbersArray[0];
+ integer1 = (Integer) number;
+
+ /*ArrayStoreException*/
+ /*String[] stringsArray = integers.toArray(new String[0]);*/
}
}
+
diff --git a/src/com/walking/lesson37_collection_list/task2/exception/ElementNotFoundException.java b/src/com/walking/lesson37_collection_list/task2/exception/ElementNotFoundException.java
new file mode 100644
index 000000000..7ca21dee3
--- /dev/null
+++ b/src/com/walking/lesson37_collection_list/task2/exception/ElementNotFoundException.java
@@ -0,0 +1,7 @@
+package com.walking.lesson37_collection_list.task2.exception;
+
+public class ElementNotFoundException extends RuntimeException {
+ public ElementNotFoundException() {
+ super("Desired element not found");
+ }
+}
diff --git a/src/com/walking/lesson37_collection_list/task2/structure/Stack.java b/src/com/walking/lesson37_collection_list/task2/structure/Stack.java
new file mode 100644
index 000000000..d7bd56111
--- /dev/null
+++ b/src/com/walking/lesson37_collection_list/task2/structure/Stack.java
@@ -0,0 +1,239 @@
+package com.walking.lesson37_collection_list.task2.structure;
+
+import com.walking.lesson37_collection_list.task2.exception.ElementNotFoundException;
+
+import java.util.*;
+import java.util.function.IntFunction;
+import java.util.function.Predicate;
+import java.util.stream.Stream;
+
+public class Stack implements Collection {
+ private Node top;
+ private int size;
+
+ public Stack() {
+ }
+
+ public Stack(E topValue) {
+ this.top = new Node<>(topValue);
+ size++;
+ }
+
+ @Override
+ public int size() {
+ return size;
+ }
+
+ @Override
+ public boolean isEmpty() {
+ return size == 0;
+ }
+
+ @Override
+ public boolean contains(Object object) {
+ Node current = top;
+
+ while (current != null) {
+ if (Objects.equals(object, current.value)) {
+ return true;
+ }
+
+ current = current.next;
+ }
+
+ return false;
+ }
+
+ @Override
+ public boolean add(E element) {
+ top = new Node<>(element, top);
+ size++;
+
+ return true;
+ }
+
+ @Override
+ public boolean remove(Object object) {
+ if (Objects.equals(top.value, object)) {
+ top = top.next;
+ size--;
+
+ return true;
+ }
+
+ Node current = top;
+
+ while (current.next != null) {
+ if (Objects.equals(current.next.value, object)) {
+ current.next = current.next.next;
+ size--;
+
+ return true;
+ }
+
+ current = current.next;
+ }
+
+ throw new ElementNotFoundException();
+ }
+
+ @Override
+ public void clear() {
+ top = null;
+ size = 0;
+ }
+
+ @Override
+ public Iterator iterator() {
+ return new Iterator() {
+ private Node current = top;
+
+ @Override
+ public boolean hasNext() {
+ return current != null;
+ }
+
+ @Override
+ public E next() {
+ if (current == null) {
+ throw new NoSuchElementException("iterator has no more elements");
+ }
+
+ Node temp = current;
+ current = current.next;
+
+ return temp.value;
+ }
+
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException("remove");
+ }
+ };
+ }
+
+ @Override
+ public Object[] toArray() {
+ Object[] values = new Object[size];
+ Node current = top;
+
+ for (int i = 0; i < values.length; i++) {
+ values[i] = current.value;
+ current = current.next;
+ }
+
+ return values;
+ }
+
+ @Override
+ public T[] toArray(T[] array) {
+ Node current = top;
+
+ if (array.length < size) {
+ array = Arrays.copyOf(array, size);
+ }
+
+ for (int i = 0; i < size; i++) {
+ array[i] = (T) current.value;
+ current = current.next;
+ }
+
+ return array;
+ }
+
+ @Override
+ public boolean containsAll(Collection> collection) {
+ for (Object object : collection) {
+ if (!this.contains(object)) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ @Override
+ public boolean addAll(Collection extends E> collection) {
+ for (E element : collection) {
+ this.add(element);
+ }
+
+ return true;
+ }
+
+ @Override
+ public boolean removeAll(Collection> collection) {
+ if (this.containsAll(collection)) {
+ for (Object object : collection) {
+ this.remove(object);
+ }
+
+ return true;
+ }
+
+ return false;
+ }
+
+ @Override
+ public boolean retainAll(Collection> collection) {
+ for (E element : this) {
+ if (!collection.contains(element)) {
+ this.remove(element);
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public T[] toArray(IntFunction generator) {
+ throw new UnsupportedOperationException("toArray(IntFunction generator)");
+ }
+
+ @Override
+ public boolean removeIf(Predicate super E> filter) {
+ throw new UnsupportedOperationException("removeIf");
+ }
+
+ @Override
+ public Spliterator spliterator() {
+ throw new UnsupportedOperationException("spliterator");
+ }
+
+ @Override
+ public Stream stream() {
+ throw new UnsupportedOperationException("stream");
+ }
+
+ @Override
+ public Stream parallelStream() {
+ throw new UnsupportedOperationException("parallelStream");
+ }
+
+ @Override
+ public String toString() {
+ StringJoiner result = new StringJoiner(",", "TOP -> ", " (size = " + size + ")");
+
+ Node current = top;
+
+ while (current != null) {
+ result.add(current.value.toString());
+ current = current.next;
+ }
+
+ return result.toString();
+ }
+
+ private static class Node {
+ private final E value;
+ private Node next;
+
+ public Node(E value) {
+ this.value = value;
+ }
+
+ public Node(E value, Node next) {
+ this.value = value;
+ this.next = next;
+ }
+ }
+}