Skip to content
Closed
Show file tree
Hide file tree
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
Expand Up @@ -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
@@ -1,26 +1,22 @@
package com.bobocode.basics;

import com.bobocode.basics.util.BaseEntity;
import com.bobocode.util.ExerciseNotCompletedException;
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;
import java.util.stream.StreamSupport;

/**
* {@link CrazyGenerics} is an exercise class. It consists of classes, interfaces and methods that should be updated
* using generics.
* <p>
* TODO: go step by step from top to bottom. Read the java doc, write code and run CrazyGenericsTest to verify your impl
* <p>
* Hint: in some cases you will need to refactor the code, like replace {@link Object} with a generic type. In order
* cases you will need to add new fields, create new classes, or add new methods. Always try to read java doc and update
* the code according to it.
* <p><p>
* <strong>TODO: to get the most out of your learning, <a href="https://www.bobocode.com">visit our website</a></strong>
* <strong></strong>
* <p>
*
* @author Taras Boychuk
Expand All @@ -33,8 +29,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> {
private T value;
private String source;
}

Expand All @@ -45,11 +41,10 @@ public static class Sourced { // todo: refactor class to introduce type paramete
* @param <T> – actual, min and max type
*/
@Data
public static class Limited {
// 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;
public static class Limited <T extends Number> {
private final T actual;
private final T min;
private final T max;
}

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

/**
Expand All @@ -70,10 +65,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>> {
private T max;

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

Expand All @@ -82,11 +77,13 @@ 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) {
if (val.compareTo(max) > 0) {
max = val;
}
}

public Object getMax() {
public T getMax() {
return max;
}
}
Expand All @@ -97,8 +94,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>> {
void process(T obj);
}

/**
Expand All @@ -108,10 +105,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>> {
void save(T entity);

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

/**
Expand All @@ -120,7 +117,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>> {
}

/**
Expand All @@ -133,7 +130,11 @@ 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<?>> {
@Override
default int compareTo(Collection<?> o) {
return Integer.compare(this.size(), o.size());
}
}

/**
Expand All @@ -147,8 +148,7 @@ static class CollectionUtil {
*
* @param list
*/
public static void print(List<Integer> list) {
// todo: refactor it so the list of any type can be printed, not only integers
public static void print(List<?> list) {
list.forEach(element -> System.out.println(" – " + element));
}

Expand All @@ -160,8 +160,9 @@ 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) {
return entities.stream()
.anyMatch(element -> element.getUuid() == null);
}

/**
Expand All @@ -173,8 +174,10 @@ 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) {
return entities.stream()
.allMatch(validationPredicate);
}

/**
Expand All @@ -187,8 +190,13 @@ 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<? extends BaseEntity> entities,
T targetEntity) {
return entities
.stream()
.filter(element -> element.getUuid().equals(targetEntity.getUuid()))
.count() > 1;
}

/**
Expand All @@ -200,7 +208,10 @@ public static boolean hasDuplicates() {
* @param <T> type of elements
* @return optional max value
*/
// todo: create a method and implement its logic manually without using util method from JDK
public static <T extends BaseEntity> Optional<T> findMax(Iterable<T> elements, Comparator<? super T> comparator) {
return StreamSupport.stream(elements.spliterator(), false)
.max(comparator);
}

/**
* findMostRecentlyCreatedEntity is a generic util method that accepts a collection of entities and returns the
Expand All @@ -214,7 +225,11 @@ public static boolean hasDuplicates() {
* @param <T> entity type
* @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, CREATED_ON_COMPARATOR)
.orElseThrow(() -> new NoSuchElementException("No present value"));
}

/**
* An util method that allows to swap two elements of any list. It changes the list so the element with the index
Expand All @@ -226,9 +241,13 @@ public static boolean hasDuplicates() {
* @param j index of the other element to swap
*/
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
swapElements(elements, i, j);
}

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

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;
import java.util.UUID;

Expand All @@ -18,4 +17,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
@@ -1,5 +1,7 @@
package com.bobocode.basics;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

/**
Expand All @@ -9,15 +11,17 @@
* It's based on the {@link Map} and provides an API that allows to put a value by type, and get a max value by type.
* <p>
* <p>
* <strong>TODO: to get the most out of your learning, <a href="https://www.bobocode.com">visit our website</a></strong>
* <strong>
* <p>
*
* @author Taras Boychuk
*/
public class HeterogeneousMaxHolder {
private Map<Class<?>, Object> maxHolderMap = new HashMap<>();

/**
* A method put stores a provided value by its type, if the value is greater than the current maximum. In other words, the logic
* A method put stores a provided value by its type, if the value is greater than the current maximum.
* In other words, the logic
* of this method makes sure that only max value is stored and everything else is ignored.
* <p>
* If the current max value is less than a provided one, or if it's null, then a provided value gets stored and the old
Expand All @@ -30,7 +34,10 @@ public class HeterogeneousMaxHolder {
* @param <T> value type parameter
* @return a smaller value among the provided value and the current maximum
*/
// todo: implement a method according to javadoc
public <T extends Comparable<? super T>> T put(Class<T> key,
T value) {
return put(key, value, Comparator.naturalOrder());
}

/**
* An overloaded method put implements the same logic using a custom comparator. A given comparator is wrapped with
Expand All @@ -44,7 +51,17 @@ public class HeterogeneousMaxHolder {
* @param <T> value type parameter
* @return a smaller value among the provided value and the current maximum
*/
// todo: implement a method according to javadoc
public <T> T put(Class<T> key,
T value,
Comparator<? super T> comparator) {
comparator = Comparator.nullsFirst(comparator);
T currentMax = key.cast(maxHolderMap.get(key));
if (comparator.compare(currentMax, value) < 0) {
maxHolderMap.put(key, value);
return currentMax;
}
return value;
}

/**
* A method getMax returns a max value by the given type. If no value is stored by this type, then it returns null.
Expand All @@ -53,5 +70,8 @@ public class HeterogeneousMaxHolder {
* @param <T> value type parameter
* @return current max value or null
*/
// todo: implement a method according to javadoc
public <T> T getMax(Class<T> key) {
T currentMax = key.cast(maxHolderMap.get(key));
return currentMax;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.bobocode.basics;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Exercise {
String value();

Level complexityLevel() default Level.BASIC;
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,6 @@
*
* @author Taras Boychuk
*/
@Exercise(value = "hello-annotation-basic")
public class HelloAnnotationsExercise { // todo: mark class with the annotation according to the javadoc
}
Loading