Skip to content
  • Sponsor bobocode-projects/java-fundamentals-exercises

  • Notifications You must be signed in to change notification settings
  • Fork 497

Completed all the topic specific tasks mentioned in the module #206

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all 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
Original file line number Diff line number Diff line change
@@ -7,18 +7,18 @@
* <p>
* todo: refactor this class so it uses generic type "T" and run {@link com.bobocode.basics.BoxTest} to verify it
*/
public class Box {
private Object value;
public class Box<T> {
private T value;

public Box(Object value) {
public Box(T value) {
this.value = value;
}

public Object getValue() {
public T getValue() {
return value;
}

public void setValue(Object value) {
public void setValue(T value) {
this.value = value;
}
}
Original file line number Diff line number Diff line change
@@ -9,12 +9,12 @@
*/
public class BoxDemoApp {
public static void main(String[] args) {
Box intBox = new Box(123);
Box intBox2 = new Box(321);
Box<Integer> intBox = new Box<>(123);
Box<Integer> intBox2 = new Box<>(321);
System.out.println((int) intBox.getValue() + (int) intBox2.getValue());

intBox.setValue(222);
intBox.setValue("abc"); // this should not be allowed
// intBox.setValue("abc"); // this should not be allowed
// the following code will compile, but will throw runtime exception
System.out.println((int) intBox.getValue() + (int) intBox2.getValue());
}
Original file line number Diff line number Diff line change
@@ -41,7 +41,7 @@ void typeParameterIsNotBounded() {
@SneakyThrows
@Order(4)
@DisplayName("Field \"value\" is \"T\"")
void valueFieldIsGeneric() {
void valueFieldIsGeneric() throws NoSuchFieldException {
var valueField = Box.class.getDeclaredField("value");
var genericType = valueField.getGenericType();

@@ -64,7 +64,7 @@ void constructorParameterIsGeneric() {
@SneakyThrows
@Order(6)
@DisplayName("Getter return type is \"T\"")
void getterReturnTypeIsGeneric() {
void getterReturnTypeIsGeneric() throws NoSuchMethodException {
var getter = Box.class.getDeclaredMethod("getValue");

assertThat(getter.getGenericReturnType().getTypeName()).isEqualTo(TYPE_PARAMETER_NAME);
@@ -74,7 +74,7 @@ void getterReturnTypeIsGeneric() {
@SneakyThrows
@Order(7)
@DisplayName("Setter parameter type is \"T\"")
void setterParameterIsGeneric() {
void setterParameterIsGeneric() throws NoSuchMethodException {
var setter = Box.class.getDeclaredMethod("setValue", Object.class);
assert (setter.getParameters().length == 1);
var parameter = setter.getParameters()[0];
Original file line number Diff line number Diff line change
@@ -5,10 +5,8 @@
import lombok.Data;

import java.io.Serializable;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.*;
import java.util.function.Predicate;

/**
* {@link CrazyGenerics} is an exercise class. It consists of classes, interfaces and methods that should be updated
@@ -33,8 +31,8 @@ public class CrazyGenerics {
* @param <T> – value type
*/
@Data
public static class Sourced { // todo: refactor class to introduce type parameter and make value generic
private Object value;
public static class Sourced<T> { // todo: refactor class to introduce type parameter and make value generic
private T value;
private String source;
}

@@ -45,11 +43,18 @@ public static class Sourced { // todo: refactor class to introduce type paramete
* @param <T> – actual, min and max type
*/
@Data
public static class Limited {
public static class Limited<T extends Number> {
// todo: refactor class to introduce type param bounded by number and make fields generic numbers
private final Object actual;
private final Object min;
private final Object max;
private final T actual;
private final T min;
private final T max;


public Limited(T actual, T min, T max) {
this.actual = actual;
this.min = min;
this.max = max;
}
}

/**
@@ -59,8 +64,9 @@ public static class Limited {
* @param <T> – source object type
* @param <R> - converted result type
*/
public interface Converter { // todo: introduce type parameters
public interface Converter<T,R> { // todo: introduce type parameters
// todo: add convert method
R convert(T source);
}

/**
@@ -70,10 +76,10 @@ public interface Converter { // todo: introduce type parameters
*
* @param <T> – value type
*/
public static class MaxHolder { // todo: refactor class to make it generic
private Object max;
public static class MaxHolder<T extends Comparable <? super T>> { // todo: refactor class to make it generic
private T max;

public MaxHolder(Object max) {
public MaxHolder(T max) {
this.max = max;
}

@@ -82,11 +88,14 @@ public MaxHolder(Object max) {
*
* @param val a new value
*/
public void put(Object val) {
throw new ExerciseNotCompletedException(); // todo: update parameter and implement the method
public void put(T val) {
// todo: update parameter and implement the method
if(val.compareTo(max) > 0){
max = val;
}
}

public Object getMax() {
public T getMax() {
return max;
}
}
@@ -97,8 +106,8 @@ public Object getMax() {
*
* @param <T> – the type of objects that can be processed
*/
interface StrictProcessor { // todo: make it generic
void process(Object obj);
interface StrictProcessor<T extends Serializable & Comparable<? super T>> { // todo: make it generic
void process(T obj);
}

/**
@@ -108,10 +117,10 @@ interface StrictProcessor { // todo: make it generic
* @param <T> – a type of the entity that should be a subclass of {@link BaseEntity}
* @param <C> – a type of any collection
*/
interface CollectionRepository { // todo: update interface according to the javadoc
void save(Object entity);
interface CollectionRepository<T extends BaseEntity ,C extends Collection<T>> { // todo: update interface according to the javadoc
void save(T entity);

Collection<Object> getEntityCollection();
C getEntityCollection();
}

/**
@@ -120,7 +129,7 @@ interface CollectionRepository { // todo: update interface according to the java
*
* @param <T> – a type of the entity that should be a subclass of {@link BaseEntity}
*/
interface ListRepository { // todo: update interface according to the javadoc
interface ListRepository<T extends BaseEntity > extends CollectionRepository<T,List<T>> { // todo: update interface according to the javadoc
}

/**
@@ -133,7 +142,10 @@ interface ListRepository { // todo: update interface according to the javadoc
*
* @param <E> a type of collection elements
*/
interface ComparableCollection { // todo: refactor it to make generic and provide a default impl of compareTo
interface ComparableCollection<E> extends Collection<E>, Comparable<Collection<?>> { // todo: refactor it to make generic and provide a default impl of compareTo
default int compareTo(Collection<?> other) { // Change parameter type
return Integer.compare(this.size(), other.size());
}
}

/**
@@ -147,7 +159,7 @@ static class CollectionUtil {
*
* @param list
*/
public static void print(List<Integer> list) {
public static void print(List<?> list) {
// todo: refactor it so the list of any type can be printed, not only integers
list.forEach(element -> System.out.println(" – " + element));
}
@@ -160,8 +172,14 @@ public static void print(List<Integer> list) {
* @param entities provided collection of entities
* @return true if at least one of the elements has null id
*/
public static boolean hasNewEntities(Collection<BaseEntity> entities) {
throw new ExerciseNotCompletedException(); // todo: refactor parameter and implement method
public static boolean hasNewEntities(Collection<? extends BaseEntity> entities) {
// todo: refactor parameter and implement method
for (BaseEntity entity : entities) {
if (entity.getUuid() == null) {
return true;
}
}
return false;
}

/**
@@ -173,8 +191,14 @@ public static boolean hasNewEntities(Collection<BaseEntity> entities) {
* @param validationPredicate criteria for validation
* @return true if all entities fit validation criteria
*/
public static boolean isValidCollection() {
throw new ExerciseNotCompletedException(); // todo: add method parameters and implement the logic
public static boolean isValidCollection(Collection<? extends BaseEntity> entities, Predicate<? super BaseEntity> validationPredicate) {
// todo: add method parameters and implement the logic
for (BaseEntity entity : entities) {
if (!validationPredicate.test(entity)) {
return false;
}
}
return true;
}

/**
@@ -187,8 +211,17 @@ public static boolean isValidCollection() {
* @param <T> entity type
* @return true if entities list contains target entity more than once
*/
public static boolean hasDuplicates() {
throw new ExerciseNotCompletedException(); // todo: update method signature and implement it
public static <T extends BaseEntity> boolean hasDuplicates(Collection<T> entities ,T targetEntity) {
// todo: update method signature and implement it
int count =0;
UUID targetUUID = targetEntity.getUuid();
for (T entity : entities) {
UUID entityUUID = entity.getUuid();
if (entityUUID.equals(targetUUID)) {
count++;
}
}
return count > 1;
}

/**
@@ -201,7 +234,15 @@ public static boolean hasDuplicates() {
* @return optional max value
*/
// todo: create a method and implement its logic manually without using util method from JDK

public static <T> Optional<T> findMax(Iterable<T> elements , Comparator<T> comparator){
T max = null;
for (T element : elements) {
if (max == null || comparator.compare(element, max) > 0) {
max = element;
}
}
return Optional.ofNullable(max);
}
/**
* findMostRecentlyCreatedEntity is a generic util method that accepts a collection of entities and returns the
* one that is the most recently created. If collection is empty,
@@ -215,7 +256,10 @@ public static boolean hasDuplicates() {
* @return an entity from the given collection that has the max createdOn value
*/
// todo: create a method according to JavaDoc and implement it using previous method

public static <T extends BaseEntity> T findMostRecentlyCreatedEntity(Collection<T> entities) {
return findMax(entities, Comparator.comparing(BaseEntity::getCreatedOn))
.orElseThrow(NoSuchElementException::new);
}
/**
* An util method that allows to swap two elements of any list. It changes the list so the element with the index
* i will be located on index j, and the element with index j, will be located on the index i.
@@ -228,7 +272,14 @@ public static boolean hasDuplicates() {
public static void swap(List<?> elements, int i, int j) {
Objects.checkIndex(i, elements.size());
Objects.checkIndex(j, elements.size());
throw new ExerciseNotCompletedException(); // todo: complete method implementation
// todo: complete method implementation
swapHelper(elements,i,j);
}

private static <T> void swapHelper(List<T> elements, int i, int j) {
T temp = elements.get(i);
elements.set(i, elements.get(j));
elements.set(j, temp);
}

}
Original file line number Diff line number Diff line change
@@ -18,4 +18,12 @@ public BaseEntity(UUID uuid) {
this.uuid = uuid;
this.createdOn = LocalDateTime.now();
}

public UUID getUuid() {
return uuid;
}

public LocalDateTime getCreatedOn() {
return createdOn;
}
}
Original file line number Diff line number Diff line change
@@ -12,6 +12,7 @@

import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.time.LocalDateTime;
@@ -70,7 +71,7 @@ void sourcedClassTypeParameterIsNotBounded() {
@SneakyThrows
@Order(4)
@DisplayName("Sourced class field \"value\" has generic type \"T\"")
void valueFieldIsGeneric() {
void valueFieldIsGeneric() throws NoSuchFieldException {
var valueField = Sourced.class.getDeclaredField("value");
var genericType = valueField.getGenericType();

@@ -144,7 +145,7 @@ void converterInterfaceSecondTypeParameterIsCalledR() {
@SneakyThrows
@Order(11)
@DisplayName("Convert method parameter \"obj\" has type \"T\"")
void converterMethodParameterHasTypeT() {
void converterMethodParameterHasTypeT() throws NoSuchMethodException {
var convertMethod = Converter.class.getDeclaredMethod("convert", Object.class);
var objParam = convertMethod.getParameters()[0];

@@ -155,7 +156,7 @@ void converterMethodParameterHasTypeT() {
@SneakyThrows
@Order(12)
@DisplayName("Convert method return type is \"R\"")
void converterMethodReturnTypeIsR() {
void converterMethodReturnTypeIsR() throws NoSuchMethodException {
var convertMethod = Converter.class.getDeclaredMethod("convert", Object.class);

assertThat(convertMethod.getGenericReturnType().getTypeName()).isEqualTo(SECOND_TYPE_PARAMETER_NAME);
@@ -237,7 +238,7 @@ void maxHolderGetMaxReturnTypeIsT() {
@Order(20)
@SneakyThrows
@DisplayName("MaxHolder put stores argument value when it's greater than max")
void maxHolderPut() {
void maxHolderPut() throws InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException {
Constructor<?> constructor = MaxHolder.class.getConstructors()[0];
var maxHolder = constructor.newInstance(10);
var putMethod = getMethodByName(MaxHolder.class, "put");
@@ -787,7 +788,7 @@ void findMostRecentlyCreatedEntityIsAGenericMethod() {
@DisplayName("findMostRecentlyCreatedEntity returns the most recently created entity")
@SneakyThrows
void findMostRecentlyCreatedEntityReturnsEntityWithMaxCreatedOnValue(List<? extends BaseEntity> entities,
BaseEntity mostRecentlyCreatedEntity) {
BaseEntity mostRecentlyCreatedEntity) throws InvocationTargetException, IllegalAccessException {
var findMostRecentlyCreatedEntityMethod = getMethodByName(CollectionUtil.class, "findMostRecentlyCreatedEntity");

var result = findMostRecentlyCreatedEntityMethod.invoke(null, entities);
Loading