Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
# Project exclude paths
/out/
/out/
/resource/
69 changes: 69 additions & 0 deletions src/com/walking/lesson37_collection_list/task1/Main.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
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.List;

/**
* Реализуйте задачу
* <a href="https://github.com/KFalcon2022/CounterAggregation">...</a>, используя ArrayList.
Expand All @@ -10,6 +15,70 @@
* Изменилось ли что-то в кодовой базе при использовании списка другой реализации?
*/
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 = "кВт*ч";

public static void main(String[] args) {
CounterService counterService = new CounterService();
counterService.displayContent();
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

замечание то же, что и ранее: сервис не должен отвечать за способ вывода


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(coldWaterCounter, gasCounter);

counterService.addCounter(hotWaterCounter);
counterService.addCountersIfAbsent(electricCounter);
counterService.addCountersIfAbsent(electricCounter);
counterService.addCounter(electricCounter);
counterService.addFirst(electricCounter);
counterService.increaseCounter(GAS_COUNTER_NAME, 100);
counterService.increaseCounter(coldWaterCounter, 10);
counterService.displayContent();

counterService.removeDuplicates();
counterService.sortByName();
counterService.removeAllZeroValue();
System.out.println("Удаляем дубликаты, счетчики с нулевыми показаниями и сортируем по алфавиту:");
counterService.displayContent();


System.out.println("Название первого в списке счетчика: " + counterService.getFirst().getName());

Counter[] allCounters = new Counter[counterService.getAllCounters().size() + 5];

counterService.getAllCounters().toArray(allCounters);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

предсоздавать массив в данном случае не обязательно

System.out.println("Переносим счетчики из списка в заранее созданный массив:");
printCounterNames(allCounters);

List<Counter> waterCounters = List.of(hotWaterCounter, coldWaterCounter);


hotWaterCounter.setValue(100);
counterService.addCounter(hotWaterCounter);
counterService.removeIfNotMatch(waterCounters);
System.out.println("Оставляем только счетчики воды:");
counterService.displayContent();
}

public static void printCounterNames(Counter[] counters) {
System.out.println("Названия счетчиков в массиве:");

for (Counter counter : counters) {
if (counter == null) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

тернарка смотрелась бы лаконичнее

System.out.println("-");
} else {
System.out.println(counter.getName());
}
}
}
}
39 changes: 39 additions & 0 deletions src/com/walking/lesson37_collection_list/task1/model/Counter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.walking.lesson37_collection_list.task1.model;

public class Counter implements Comparable<Counter> {
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());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
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<Counter> counters;
public CounterService(Counter... counters) {
this.counters = new Vector<>(Arrays.asList(counters));
} */

private final ArrayList<Counter> counters;

public CounterService(Counter... counters) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вполне можно и параметром принимать лист. Опционально

this.counters = new ArrayList<>(Arrays.asList(counters));
}

public List<Counter> getAllCounters() {
return counters;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

на будущее - зачастую хорошей практикой принимается отдавать копию коллекции - на случай, если необходимо ограничить бесконтрольное изменение такого хранилища. Тогда добавление и иные изменения коллекции ограничены апи управляющего класса (здесь - сервиса), а на чтение всегда будет отдаваться копия, изменение которой не повлияет на основную коллекцию

}

public Counter getFirst() {
return counters.get(0);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

с 21 джавы можно проще

}

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<Counter> candidates = new ArrayList<>(Arrays.asList(counters));
candidates.removeAll(this.counters);
return this.counters.addAll(candidates);
}

public boolean removeIfNotMatch(Collection<? extends Counter> sample) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

чтобы потыкать функциональность листов - норм, но в целом такая семантика вызывает вопросы

return counters.retainAll(sample);
}

public boolean removeDuplicates() {
List<Counter> uniques = getUniques();

if (uniques.size() == counters.size()) {
return false;
}

counters.clear();
counters.addAll(uniques);
return true;
}

private List<Counter> getUniques() {
List<Counter> uniques = new ArrayList<>();

for (Counter counter : counters) {
if (!uniques.contains(counter)) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

у тебя же вроде не переопределен equals(). Будет криво работать

uniques.add(counter);
}
}

return uniques;
}

public boolean removeAllZeroValue() {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

непонятное название, смысл становится прозрачным только после погружения в тело метода

List<Counter> zeroValues = getZeroValues();

if (zeroValues.size() == 0) {
return false;
}

counters.removeAll(zeroValues);
return true;
}

private List<Counter> getZeroValues() {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

советую располагать методы в соответствие с модификатором доступа - сначала публичные, потом протектед и т.д.

List<Counter> zeroValues = new ArrayList<>();

for (Counter counter : counters) {
if (counter.getValue() == 0) {
zeroValues.add(counter);
}
}

return zeroValues;
}

public void sortByName() {
counters.sort(Comparator.naturalOrder());
}

public void sortBy(Comparator<Counter> 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);

if (counter == null) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

тернарный оператор?

return null;
}

return 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);

if (counter == null) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

и здесь

return null;
}

return 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);

if (counter == null) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

.

return null;
}

return incrementCounter(counter);
}

public Counter incrementCounter(Counter counter) {
increaseCounter(counter, 1);
return counter;
}

public Counter decrementCounter(String name) {
Counter counter = getCounterByName(name);

if (counter == null) {
return null;
}

return decrementCounter(counter);
}

public Counter decrementCounter(Counter counter) {
decreaseCounter(counter, 1);
return counter;
}

public Counter reset(String name) {
Counter counter = getCounterByName(name);

if (counter == null) {
return null;
}

return reset(counter);
}

public Counter reset(Counter counter) {
counter.setValue(0);

return counter;
}

public void displayContent() {
System.out.printf("Всего счетчиков: %s\n%s\n", counters.size(), "-".repeat(20));

if (counters.isEmpty()) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

отписывал выше

System.out.println("Добавьте счетчики для работы с ними.");
} else {
printCounterValues();
}

System.out.println("-".repeat(20));
}

private void printCounterValues() {
for (Counter counter : counters) {
System.out.printf("%s: %d %s\n", counter.getName(), counter.getValue(), counter.getUnitOfMeasure());
}
}
}
Loading