Add Type Parameter vs Wildcard in Java Generics (#12988)

* Add Type Parameter vs Wildcard in Java Generics

* Fix Logger variable and code format

* Update Cat class

* Add missing import

* Add warning comment
This commit is contained in:
apeterlic 2022-12-12 08:35:27 +01:00 committed by GitHub
parent 4fc53df118
commit 29d97308f6
6 changed files with 207 additions and 0 deletions

View File

@ -0,0 +1,22 @@
package com.baeldung.generics;
abstract class Animal {
protected final String type;
protected final String name;
protected Animal(String type, String name) {
this.type = type;
this.name = name;
}
abstract String makeSound();
public String getType() {
return type;
}
public String getName() {
return name;
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.generics;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class AnimalDemo {
private static final Logger logger = LoggerFactory.getLogger(AnimalDemo.class);
public static void main(String[] args) {
List<Cat> cats = new ArrayList<>();
cats.add(new Cat("Persian", "Bono"));
cats.add(new Cat("Egyptian", "Lulu"));
cats.add(new Cat("Siamese", "Ra"));
order(cats);
logger.info("Ordered cats: {}", cats);
}
public static <T extends Animal & Comparable<T>> void order(List<T> list) {
list.sort(Comparable::compareTo);
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.generics;
import java.util.Objects;
class Cat extends Animal implements Comparable<Cat> {
public Cat(String type, String name) {
super(type, name);
}
@Override
public String makeSound() {
return "Meow";
}
/**
* Warning: Inconsistent with the equals method.
*/
@Override
public int compareTo(Cat cat) {
return this.getName().length() - cat.getName().length();
}
@Override
public String toString() {
return "Cat{" + "type='" + type + '\'' + ", name='" + name + '\'' + '}';
}
@Override
public int hashCode() {
return Objects.hash(type, name);
}
@Override
public boolean equals(Object o) {
if(o == this) return true;
if(!(o instanceof Cat)) return false;
Cat cat = (Cat) o;
return type.equals(cat.type) && name.equals(cat.name);
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.generics;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CollectionUtils {
private CollectionUtils() {
}
public static <T> void print(T item) {
System.out.println(item);
}
public static void swap(List<?> list, int src, int des) {
swapHelper(list, src, des);
}
private static <E> void swapHelper(List<E> list, int src, int des) {
list.set(src, list.set(des, list.get(src)));
}
public static <E> List<E> mergeTypeParameter(List<? extends E> listOne, List<? extends E> listTwo) {
return Stream.concat(listOne.stream(), listTwo.stream())
.collect(Collectors.toList());
}
public static <E> List<? extends E> mergeWildcard(List<? extends E> listOne, List<? extends E> listTwo) {
return Stream.concat(listOne.stream(), listTwo.stream())
.collect(Collectors.toList());
}
public static long sum(List<Number> numbers) {
return numbers.stream()
.mapToLong(Number::longValue)
.sum();
}
public static <T extends Number> long sumTypeParameter(List<T> numbers) {
return numbers.stream()
.mapToLong(Number::longValue)
.sum();
}
public static long sumWildcard(List<? extends Number> numbers) {
return numbers.stream()
.mapToLong(Number::longValue)
.sum();
}
public static void addNumber(List<? super Integer> list, Integer number) {
list.add(number);
}
}

View File

@ -0,0 +1,48 @@
package com.baeldung.generics;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class CollectionUtilsDemo {
private static final Logger logger = LoggerFactory.getLogger(CollectionUtilsDemo.class);
public static void main(String[] args) {
CollectionUtils.print("Baeldung");
List<Number> numbers1 = new ArrayList<>();
numbers1.add(5);
numbers1.add(10L);
List<Number> numbers2 = new ArrayList<>();
numbers2.add(15f);
numbers2.add(20.0);
List<Number> numbersMerged = CollectionUtils.mergeTypeParameter(numbers1, numbers2);
logger.info("Merged numbers: {}", numbersMerged);
List<Number> numbers = new ArrayList<>();
numbers.add(5);
numbers.add(10L);
numbers.add(15f);
numbers.add(20.0);
logger.info("Sum: {}", CollectionUtils.sum(numbers));
logger.info("Sum (wildcard): {}", CollectionUtils.sumWildcard(numbers));
logger.info("Sum (type parameter): {}", CollectionUtils.sumTypeParameter(numbers));
List<Integer> integers = new ArrayList<>();
integers.add(5);
logger.info("Sum integers (wildcard): {}", CollectionUtils.sumWildcard(integers));
CollectionUtils.addNumber(numbers, 4);
CollectionUtils.addNumber(integers, 5);
logger.info("Before swap: {}", numbers);
CollectionUtils.swap(numbers, 0, 1);
logger.info("After swap: {}", numbers);
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.generics;
public class Dog extends Animal {
public Dog(String type, String name) {
super(type, name);
}
@Override
public String makeSound() {
return "Wuf";
}
}