Skip to content

Commit 5299e37

Browse files
committed
filling class SympleAuthorRepository and debugging its methods in main()
1 parent 8461109 commit 5299e37

3 files changed

Lines changed: 175 additions & 38 deletions

File tree

src/main/java/com/epam/izh/rd/online/Main.java

Lines changed: 55 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,54 +1,19 @@
11
package com.epam.izh.rd.online;
22

33
import com.epam.izh.rd.online.entity.Author;
4+
import com.epam.izh.rd.online.repository.SimpleAuthorRepository;
45
import com.sun.org.apache.xerces.internal.xs.datatypes.ObjectList;
56
import com.sun.xml.internal.ws.addressing.WsaActionUtil;
67
import org.springframework.util.Assert;
78
import org.springframework.util.SocketUtils;
89

10+
import java.time.LocalDate;
911
import java.util.ArrayList;
1012

1113
public class Main {
1214

1315
public static void main(String[] args) {
1416

15-
{/* SECTION FOR DEBUGGING CLASS Author */
16-
//
17-
// Author author1 = new Author();
18-
//
19-
// author1.setName("Yaroslav");
20-
// author1.setCountry("Russia");
21-
//
22-
// class FreakAuthor extends Author {
23-
// public FreakAuthor(String name) {
24-
// this.setName(name);
25-
// }
26-
//
27-
// @Override
28-
// public int hashCode() {
29-
// return Object.class.hashCode();
30-
// }
31-
//
32-
// }
33-
//
34-
// FreakAuthor freak = new FreakAuthor("John");
35-
//
36-
// System.out.println("author1.objectToString(): " + author1.objectToString());
37-
// System.out.println("author1.toString(): " + author1.toString());
38-
// System.out.println("\n" + "author1 is the following " + author1.toString());
39-
//
40-
// System.out.println("\nHash code1 for author " + author1.getName() + " is " + author1.hashCode());
41-
// System.out.println("Hash code2 for author " + author1.getName() + " is " + author1.hashCode());
42-
// System.out.println("Hash code3 for author " + author1.getName() + " is " + author1.hashCode());
43-
//
44-
// System.out.println("\nHash code1 for author " + freak.getName() + " is " + freak.hashCode());
45-
// System.out.println("Hash code2 for author " + freak.getName() + " is " + freak.hashCode());
46-
// System.out.println("Hash code3 for author " + freak.getName() + " is " + freak.hashCode());
47-
// System.out.println("author1.ToStringHash(): " + author1.ToStringHash());
48-
49-
}/* END OF DEBUGGING CLASS Author */
50-
51-
5217
{/* SECTION FOR PLAYING WITH ASSERTIONS */
5318

5419
System.out.println("\n/* SECTION FOR PLAYING WITH ASSERTIONS */\n");
@@ -305,6 +270,59 @@ void subtleMethod( byte par ) {
305270

306271
}/* END OF DEBUGGING BINDING METHODS */
307272

273+
274+
{/* SECTION FOR DEBUGGING CLASSES */
275+
276+
System.out.println("\n/* SECTION FOR DEBUGGING CLASSES */\n");
277+
278+
Author author1 = new Author("Yaroslav", "Kozlov", LocalDate.of(1974,10,05), "Russia");
279+
Author author2 = new Author("James", "Bond", null, "UK");
280+
Author author3 = new Author("Wolfgang", "Mozart", LocalDate.of(1756,01,27), "Austria");
281+
282+
SimpleAuthorRepository rep4Authors = new SimpleAuthorRepository();
283+
284+
System.out.println("author1.toString(): " + author1.toString());
285+
System.out.println("author2.toString(): " + author2.toString());
286+
System.out.println("author3.toString(): " + author3.toString());
287+
288+
System.out.println("\nNumber of authors saved in repository is " + rep4Authors.count());
289+
290+
System.out.println("\nSaving author1 in repository");
291+
rep4Authors.save(author1);
292+
System.out.println("Number of authors saved in repository is " + rep4Authors.count());
293+
294+
System.out.println("\nSaving author2 in repository");
295+
rep4Authors.save(author2);
296+
System.out.println("Number of authors saved in repository is " + rep4Authors.count());
297+
298+
System.out.println("\nSaving author3 in repository");
299+
rep4Authors.save(author3);
300+
System.out.println("Number of authors saved in repository is " + rep4Authors.count());
301+
302+
Author found;
303+
found = rep4Authors.findByFullName("James", "Bond");
304+
System.out.println("\nIs James Bond in repository? " + (found == null ? "No: " : "Yes: ") + found);
305+
found = rep4Authors.findByFullName("Vasya", "Pupkin");
306+
System.out.println("Is Vasya Pupkin in repository? " + (found == null ? "No: " : "Yes: ") + found);
307+
308+
Author vasya = new Author("Vasya","Pupkin",null, null);
309+
System.out.println("\nSaving author Vasya Pupkin in repository");
310+
rep4Authors.save(vasya);
311+
System.out.println("Number of authors saved in repository is " + rep4Authors.count());
312+
313+
found = rep4Authors.findByFullName("Vasya", "Pupkin");
314+
System.out.println("Is Vasya Pupkin in repository? " + (found == null ? "No: " : "Yes: ") + found);
315+
316+
System.out.println("\nRemoving author Vasya Pupkin from repository");
317+
rep4Authors.remove(vasya);
318+
System.out.println("Number of authors saved in repository is " + rep4Authors.count());
319+
found = rep4Authors.findByFullName("Vasya", "Pupkin");
320+
System.out.println("Is Vasya Pupkin in repository? " + (found == null ? "No: " : "Yes: ") + found);
321+
322+
System.out.println("\n/* END OF DEBUGGING CLASSES */\n");
323+
324+
}/* END OF DEBUGGING CLASSES */
325+
308326
System.exit(0);
309327
}
310328

src/main/java/com/epam/izh/rd/online/entity/Author.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ public int hashCode() {
9191

9292
@Override
9393
public String toString() {
94-
return "instance of class Author: { " +
94+
return "instance of class Author = { " +
9595
"name='" + name + '\'' +
9696
", lastName='" + lastName + '\'' +
9797
", birthdate=" + birthdate +
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
package com.epam.izh.rd.online.repository;
2+
3+
import com.epam.izh.rd.online.entity.Author;
4+
5+
import java.util.Arrays;
6+
7+
/**
8+
* Класс SimpleAuthorRepository репозитория для хранения данных об авторах.
9+
*
10+
* Необходимо:
11+
* 1) Имплементировать в данном классе интерфейс AuthorRepository
12+
* 2) Добавить все методы интерфейса (пока можно не писать реализацию)
13+
* 3) Добавить приватное поле "Author[] authors" для хранения авторов
14+
* 4) Инициалазировать его пустым массивом
15+
* 5) Написать в классе SimpleAuthorRepository реализацию для всех методов (коллекции не используем, работаем только с массивами)
16+
*/
17+
public class SimpleAuthorRepository implements AuthorRepository {
18+
19+
private Author[] authors = {};
20+
private int counter = 0;
21+
22+
/**
23+
* Метод должен сохранять автора в массив authors.
24+
* Массив при каждом сохранении должен увеличиваться в размере ровно на 1.
25+
* То есть он ровно того размера, сколько сущностей мы в него сохранили.
26+
* <p>
27+
* Если на вход для сохранения приходит автор, который уже есть в массиве (сохранен), то автор не сохраняется и
28+
* метод возвращает false.
29+
* <p>
30+
* Можно сравнивать только по полному имени (имя и фамилия), считаем, что двух авторов
31+
* с одинаковыми именем и фамилией быть не может.
32+
* Подсказка - можно использовать для проверки метод findByFullName.
33+
* <p>
34+
* Если сохранение прошло успешно, метод должен вернуть true.
35+
*/
36+
@Override
37+
public boolean save(Author author) {
38+
39+
if (findByFullName(author.getName(), author.getLastName()) != null) {
40+
return false;
41+
} else {
42+
43+
Author[] temp;
44+
temp = authors;
45+
authors = new Author[counter + 1];
46+
47+
for (int i = 0; i < counter; i++) {
48+
authors[i] = temp[i];
49+
}
50+
51+
authors[counter++] = author;
52+
return true;
53+
}
54+
}
55+
56+
/**
57+
* Метод должен находить в массиве authors автора по имени и фамилии (считаем, что двух авторов
58+
* с одинаковыми именем и фамилией быть не может.)
59+
* <p>
60+
* Если автор с таким именем и фамилией найден - возвращаем его, если же не найден, метод должен вернуть null.
61+
*/
62+
@Override
63+
public Author findByFullName(String name, String lastname) {
64+
65+
if (authors.length == 0) {
66+
return null;
67+
}
68+
69+
for(Author a : authors) {
70+
if ((a.getName() == name) && (a.getLastName() == lastname)) {
71+
return a;
72+
}
73+
}
74+
75+
return null;
76+
}
77+
78+
/**
79+
* Метод должен удалять автора из массива authors, если он там имеется.
80+
* Автора опять же, можно определять только по совпадению имении и фамилии.
81+
* <p>
82+
* Важно: при удалении автора из массива размер массива должен уменьшиться!
83+
* То есть, если мы сохранили 2 авторов и вызвали count() (метод ниже), то он должен вернуть 2.
84+
* Если после этого мы удалили 1 автора, метод count() должен вернуть 1.
85+
* <p>
86+
* Если автор был найден и удален, метод должен вернуть true, в противном случае, если автор не был найден, метод
87+
* должен вернуть false.
88+
*/
89+
@Override
90+
public boolean remove(Author author) {
91+
92+
if (findByFullName(author.getName(), author.getLastName()) == null) {
93+
return false;
94+
} else {
95+
96+
Author[] temp;
97+
temp = authors;
98+
authors = new Author[counter - 1];
99+
100+
for (int i = 0, k = 0; i < counter; i++) {
101+
if(temp[i] == author) {
102+
continue;
103+
}
104+
authors[k++] = temp[i];
105+
}
106+
107+
counter--;
108+
return true;
109+
}
110+
}
111+
112+
/**
113+
* Метод возвращает количество сохраненных сущностей в массиве authors.
114+
*/
115+
@Override
116+
public int count() {
117+
return counter;
118+
}
119+
}

0 commit comments

Comments
 (0)