Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Amit Bhave
2021-02-09 19:19:03 +05:30
101 changed files with 1963 additions and 170 deletions
@@ -26,7 +26,7 @@ public class Product {
return tags;
}
public Product addTagsOfOtherProdcut(Product product) {
public Product addTagsOfOtherProduct(Product product) {
this.tags.addAll(product.getTags());
return this;
}
@@ -100,11 +100,11 @@ public class Product {
HashMap<String, Product> productsByName = new HashMap<>();
Product eBike2 = new Product("E-Bike", "A bike with a battery");
eBike2.getTags().add("sport");
productsByName.merge("E-Bike", eBike2, Product::addTagsOfOtherProdcut);
productsByName.merge("E-Bike", eBike2, Product::addTagsOfOtherProduct);
//Prior to Java 8:
if(productsByName.containsKey("E-Bike")) {
productsByName.get("E-Bike").addTagsOfOtherProdcut(eBike2);
productsByName.get("E-Bike").addTagsOfOtherProduct(eBike2);
} else {
productsByName.put("E-Bike", eBike2);
}
@@ -117,7 +117,7 @@ public class Product {
productsByName.compute("E-Bike", (k,v) -> {
if(v != null) {
return v.addTagsOfOtherProdcut(eBike2);
return v.addTagsOfOtherProduct(eBike2);
} else {
return eBike2;
}
@@ -125,7 +125,7 @@ public class Product {
//Prior to Java 8:
if(productsByName.containsKey("E-Bike")) {
productsByName.get("E-Bike").addTagsOfOtherProdcut(eBike2);
productsByName.get("E-Bike").addTagsOfOtherProduct(eBike2);
} else {
productsByName.put("E-Bike", eBike2);
}
@@ -1,3 +1,4 @@
### Relevant Articles:
- [Binary Semaphore vs Reentrant Lock](https://www.baeldung.com/java-binary-semaphore-vs-reentrant-lock)
- [Bad Practices With Synchronization](https://www.baeldung.com/java-synchronization-bad-practices)
@@ -0,0 +1,35 @@
package com.baeldung.synchronizationbadpractices;
public class AnimalBadPractice {
private String name;
private String owner;
public String getName() {
return name;
}
public String getOwner() {
return owner;
}
public synchronized void setName(String name) {
this.name = name;
}
public void setOwner(String owner) {
synchronized(this) {
this.owner = owner;
}
}
public AnimalBadPractice() {
}
public AnimalBadPractice(String name, String owner) {
this.name = name;
this.owner = owner;
}
}
@@ -0,0 +1,42 @@
package com.baeldung.synchronizationbadpractices;
public class AnimalSolution {
private final Object objLock1 = new Object();
private final Object objLock2 = new Object();
private String name;
private String owner;
public String getName() {
return name;
}
public String getOwner() {
return owner;
}
public void setName(String name) {
synchronized(objLock1) {
this.name = name;
}
}
public void setOwner(String owner) {
synchronized(objLock2) {
this.owner = owner;
}
}
public AnimalSolution() {
}
public AnimalSolution(String name, String owner) {
this.name = name;
this.owner = owner;
}
}
@@ -0,0 +1,51 @@
package com.baeldung.synchronizationbadpractices;
public class SynchronizationBadPracticeExample {
public void stringBadPractice1() {
String stringLock = "LOCK_STRING";
synchronized (stringLock) {
// ...
}
}
private final String stringLock = "LOCK_STRING";
public void stringBadPractice2() {
synchronized (stringLock) {
// ...
}
}
private final String internedStringLock = new String("LOCK_STRING").intern();
public void stringBadPractice3() {
synchronized (internedStringLock) {
// ...
}
}
private final Boolean booleanLock = Boolean.FALSE;
public void booleanBadPractice() {
synchronized (booleanLock) {
// ...
}
}
private int count = 0;
private final Integer intLock = count;
public void boxedPrimitiveBadPractice() {
synchronized (intLock) {
count++;
// ...
}
}
public void classBadPractice() throws InterruptedException {
AnimalBadPractice animalObj = new AnimalBadPractice("Tommy", "John");
synchronized(animalObj) {
while (true) {
Thread.sleep(Integer.MAX_VALUE);
}
}
}
}
@@ -0,0 +1,30 @@
package com.baeldung.synchronizationbadpractices;
public class SynchronizationSolutionExample {
private final String stringLock = new String("LOCK_STRING");
public void stringSolution() {
synchronized (stringLock) {
// ...
}
}
private int count = 0;
private final Integer intLock = new Integer(count);
public void boxedPrimitiveSolution() {
synchronized(intLock) {
count++;
// ...
}
}
private static int staticCount = 0;
private static final Object staticObjLock = new Object();
public void staticVariableSolution() {
synchronized(staticObjLock) {
staticCount++;
// ...
}
}
}
@@ -11,4 +11,5 @@ This module contains articles about working with the Java Virtual Machine (JVM).
- [Where Is the Array Length Stored in JVM?](https://www.baeldung.com/java-jvm-array-length)
- [Memory Address of Objects in Java](https://www.baeldung.com/java-object-memory-address)
- [List All Classes Loaded in a Specific Class Loader](https://www.baeldung.com/java-list-classes-class-loader)
- [An Introduction to the Constant Pool in the JVM](https://www.baeldung.com/jvm-constant-pool)
- More articles: [[<-- prev]](/core-java-modules/core-java-jvm)
@@ -0,0 +1,16 @@
package com.baeldung.compareto;
public class BankAccount implements Comparable<BankAccount> {
private final int balance;
public BankAccount(int balance) {
this.balance = balance;
}
@Override
public int compareTo(BankAccount anotherAccount) {
return this.balance - anotherAccount.balance;
}
}
@@ -0,0 +1,16 @@
package com.baeldung.compareto;
public class BankAccountFix implements Comparable<BankAccountFix> {
private final int balance;
public BankAccountFix(int balance) {
this.balance = balance;
}
@Override
public int compareTo(BankAccountFix anotherAccount) {
return Integer.compare(this.balance, anotherAccount.balance);
}
}
@@ -0,0 +1,32 @@
package com.baeldung.compareto;
public class FootballPlayer implements Comparable<FootballPlayer> {
private final String name;
private final int goalsScored;
public FootballPlayer(String name, int goalsScored) {
this.name = name;
this.goalsScored = goalsScored;
}
public String getName() {
return name;
}
@Override
public int compareTo(FootballPlayer anotherPlayer) {
return Integer.compare(this.goalsScored, anotherPlayer.goalsScored);
}
@Override
public boolean equals(Object object) {
if (this == object)
return true;
if (object == null || getClass() != object.getClass())
return false;
FootballPlayer player = (FootballPlayer) object;
return name.equals(player.name);
}
}
@@ -0,0 +1,12 @@
package com.baeldung.compareto;
public class HandballPlayer {
private final String name;
private final int height;
public HandballPlayer(String name, int height) {
this.name = name;
this.height = height;
}
}
@@ -0,0 +1,25 @@
package com.baeldung.compareto;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.assertj.core.api.Assertions.assertThat;
public class ArraysSortingUnitTest {
@Test
public void givenArrayOfNumbers_whenSortingArray_thenNumbersAreSortedAscending() {
int[] numbers = new int[] {5, 3, 9, 11, 1, 7};
Arrays.sort(numbers);
assertThat(numbers).containsExactly(1, 3, 5, 7, 9, 11);
}
@Test
public void givenArrayOfStrings_whenSortingArray_thenStringsAreSortedAlphabetically() {
String[] players = new String[] {"ronaldo", "modric", "ramos", "messi"};
Arrays.sort(players);
assertThat(players).containsExactly("messi", "modric", "ramos", "ronaldo");
}
}
@@ -0,0 +1,25 @@
package com.baeldung.compareto;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class BankAccountFixUnitTest {
@Test
public void givenComparisonBasedImpl_whenUsingSmallIntegers_thenComparisonWorks() {
BankAccountFix accountOne = new BankAccountFix(5000);
BankAccountFix accountTwo = new BankAccountFix(1000);
int comparison = accountOne.compareTo(accountTwo);
assertThat(comparison).isPositive();
}
@Test
public void givenComparisonBasedImpl_whenUsingLargeIntegers_thenComparisonWorks() {
BankAccountFix accountOne = new BankAccountFix(1900000000);
BankAccountFix accountTwo = new BankAccountFix(-2000000000);
int comparison = accountOne.compareTo(accountTwo);
assertThat(comparison).isPositive();
}
}
@@ -0,0 +1,25 @@
package com.baeldung.compareto;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.*;
public class BankAccountUnitTest {
@Test
public void givenSubtractionBasedImpl_whenUsingSmallIntegers_thenComparisonWorks() {
BankAccount accountOne = new BankAccount(5000);
BankAccount accountTwo = new BankAccount(1000);
int comparison = accountOne.compareTo(accountTwo);
assertThat(comparison).isPositive();
}
@Test
public void givenSubtractionBasedImpl_whenUsingLargeIntegers_thenComparisonBreaks() {
BankAccount accountOne = new BankAccount(1900000000);
BankAccount accountTwo = new BankAccount(-2000000000);
int comparison = accountOne.compareTo(accountTwo);
assertThat(comparison).isNegative();
}
}
@@ -0,0 +1,57 @@
package com.baeldung.compareto;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;
import static org.assertj.core.api.Assertions.assertThat;
public class FootballPlayerUnitTest {
@Test
public void givenInconsistentCompareToAndEqualsImpl_whenUsingSortedSet_thenSomeElementsAreNotAdded() {
FootballPlayer messi = new FootballPlayer("Messi", 800);
FootballPlayer ronaldo = new FootballPlayer("Ronaldo", 800);
TreeSet<FootballPlayer> set = new TreeSet<>();
set.add(messi);
set.add(ronaldo);
assertThat(set).hasSize(1);
assertThat(set).doesNotContain(ronaldo);
}
@Test
public void givenCompareToImpl_whenUsingCustomComparator_thenComparatorLogicIsApplied() {
FootballPlayer ronaldo = new FootballPlayer("Ronaldo", 900);
FootballPlayer messi = new FootballPlayer("Messi", 800);
FootballPlayer modric = new FootballPlayer("Modric", 100);
List<FootballPlayer> players = Arrays.asList(ronaldo, messi, modric);
Comparator<FootballPlayer> nameComparator = Comparator.comparing(FootballPlayer::getName);
Collections.sort(players, nameComparator);
assertThat(players).containsExactly(messi, modric, ronaldo);
}
@Test
public void givenCompareToImpl_whenSavingElementsInTreeMap_thenKeysAreSortedUsingCompareTo() {
FootballPlayer ronaldo = new FootballPlayer("Ronaldo", 900);
FootballPlayer messi = new FootballPlayer("Messi", 800);
FootballPlayer modric = new FootballPlayer("Modric", 100);
Map<FootballPlayer, String> players = new TreeMap<>();
players.put(ronaldo, "forward");
players.put(messi, "forward");
players.put(modric, "midfielder");
assertThat(players.keySet()).containsExactly(modric, messi, ronaldo);
}
}
@@ -0,0 +1,20 @@
package com.baeldung.compareto;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
public class HandballPlayerUnitTest {
@Test
public void givenComparableIsNotImplemented_whenSortingArray_thenExceptionIsThrown() {
HandballPlayer duvnjak = new HandballPlayer("Duvnjak", 197);
HandballPlayer hansen = new HandballPlayer("Hansen", 196);
HandballPlayer[] players = new HandballPlayer[] {duvnjak, hansen};
assertThatExceptionOfType(ClassCastException.class).isThrownBy(() -> Arrays.sort(players));
}
}
@@ -7,3 +7,4 @@ This module contains articles about generics in Java
- [Type Erasure in Java Explained](https://www.baeldung.com/java-type-erasure)
- [Raw Types in Java](https://www.baeldung.com/raw-types-java)
- [Super Type Tokens in Java Generics](https://www.baeldung.com/java-super-type-tokens)
- [Java Warning “unchecked conversion”](https://www.baeldung.com/java-unchecked-conversion)
@@ -13,4 +13,32 @@
<name>core-java-lang-oop-generics</name>
<packaging>jar</packaging>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<compilerArguments>
<Xlint:unchecked/>
</compilerArguments>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
</project>
@@ -0,0 +1,45 @@
package com.baeldung.uncheckedconversion;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
public class UncheckedConversion {
public static List getRawList() {
List result = new ArrayList();
result.add("I am the 1st String.");
result.add("I am the 2nd String.");
result.add("I am the 3rd String.");
return result;
}
public static List getRawListWithMixedTypes() {
List result = new ArrayList();
result.add("I am the 1st String.");
result.add("I am the 2nd String.");
result.add("I am the 3rd String.");
result.add(new Date());
return result;
}
public static <T> List<T> castList(Class<? extends T> clazz, Collection<?> rawCollection) {
List<T> result = new ArrayList<>(rawCollection.size());
for (Object o : rawCollection) {
try {
result.add(clazz.cast(o));
} catch (ClassCastException e) {
// log the exception or other error handling
}
}
return result;
}
public static <T> List<T> castList2(Class<? extends T> clazz, Collection<?> rawCollection) throws ClassCastException {
List<T> result = new ArrayList<>(rawCollection.size());
for (Object o : rawCollection) {
result.add(clazz.cast(o));
}
return result;
}
}
@@ -0,0 +1,39 @@
package com.baeldung.uncheckedconversion;
import org.junit.Assert;
import org.junit.Test;
import java.util.List;
public class UncheckedConversionUnitTest {
@Test
public void givenRawList_whenAssignToTypedList_shouldHaveCompilerWarning() {
List<String> fromRawList = UncheckedConversion.getRawList();
Assert.assertEquals(3, fromRawList.size());
Assert.assertEquals("I am the 1st String.", fromRawList.get(0));
}
@Test(expected = ClassCastException.class)
public void givenRawList_whenListHasMixedType_shouldThrowClassCastException() {
List<String> fromRawList = UncheckedConversion.getRawListWithMixedTypes();
Assert.assertEquals(4, fromRawList.size());
Assert.assertFalse(fromRawList.get(3).endsWith("String."));
}
@Test
public void givenRawList_whenAssignToTypedListAfterCallingCastList_shouldOnlyHaveElementsWithExpectedType() {
List rawList = UncheckedConversion.getRawListWithMixedTypes();
List<String> strList = UncheckedConversion.castList(String.class, rawList);
Assert.assertEquals(4, rawList.size());
Assert.assertEquals("One element with the wrong type has been filtered out.", 3, strList.size());
Assert.assertTrue(strList.stream().allMatch(el -> el.endsWith("String.")));
}
@Test(expected = ClassCastException.class)
public void givenRawListWithWrongType_whenAssignToTypedListAfterCallingCastList2_shouldThrowException() {
List rawList = UncheckedConversion.getRawListWithMixedTypes();
UncheckedConversion.castList2(String.class, rawList);
}
}
@@ -0,0 +1,4 @@
package com.baeldung.reflection.check.abstractclass;
public interface InterfaceExample {
}
@@ -1,16 +1,36 @@
package com.baeldung.reflection.check.abstractclass;
import java.lang.reflect.Modifier;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Modifier;
import java.util.Date;
class AbstractExampleUnitTest {
@Test
void givenAbstractClass_whenCheckModifierIsAbstract_thenTrue() throws Exception {
void givenAbstractClass_whenCheckModifierIsAbstract_thenTrue() {
Class<AbstractExample> clazz = AbstractExample.class;
Assertions.assertTrue(Modifier.isAbstract(clazz.getModifiers()));
}
@Test
void givenInterface_whenCheckModifierIsAbstract_thenTrue() {
Class<InterfaceExample> clazz = InterfaceExample.class;
Assertions.assertTrue(Modifier.isAbstract(clazz.getModifiers()));
}
@Test
void givenAbstractClass_whenCheckIsAbstractClass_thenTrue() {
Class<AbstractExample> clazz = AbstractExample.class;
int mod = clazz.getModifiers();
Assertions.assertTrue(Modifier.isAbstract(mod) && !Modifier.isInterface(mod));
}
@Test
void givenConcreteClass_whenCheckIsAbstractClass_thenFalse() {
Class<Date> clazz = Date.class;
int mod = clazz.getModifiers();
Assertions.assertFalse(Modifier.isAbstract(mod) && !Modifier.isInterface(mod));
}
}
@@ -0,0 +1,23 @@
package com.baeldung.egd;
import java.security.SecureRandom;
/**
* JavaSecurityEgdTester - run this with JVM parameter java.security.egd, e.g.:
* java -Djava.security.egd=file:/dev/urandom -cp . com.baeldung.egd.JavaSecurityEgdTester
*/
public class JavaSecurityEgdTester {
public static final double NANOSECS = 1000000000.0;
public static final String JAVA_SECURITY_EGD = "java.security.egd";
public static void main(String[] args) {
SecureRandom secureRandom = new SecureRandom();
long start = System.nanoTime();
byte[] randomBytes = new byte[256];
secureRandom.nextBytes(randomBytes);
double duration = (System.nanoTime() - start) / NANOSECS;
String message = String.format("java.security.egd=%s took %.3f seconds and used the %s algorithm", System.getProperty(JAVA_SECURITY_EGD), duration, secureRandom.getAlgorithm());
System.out.println(message);
}
}
+1
View File
@@ -2,3 +2,4 @@
- [Java Map With Case-Insensitive Keys](https://www.baeldung.com/java-map-with-case-insensitive-keys)
- [Using a Byte Array as Map Key in Java](https://www.baeldung.com/java-map-key-byte-array)
- [Using the Map.Entry Java Class](https://www.baeldung.com/java-map-entry)
@@ -0,0 +1,35 @@
package com.baeldung.map.entry;
public class Book {
private String title;
private String author;
public Book(String title, String author) {
this.title = title;
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
@Override
public String toString() {
return "Book{" +
"title='" + title + '\'' +
", author='" + author + '\'' +
'}';
}
}
@@ -0,0 +1,34 @@
package com.baeldung.map.entry;
import java.util.HashMap;
import java.util.Map;
public class MapEntryEfficiencyExample {
public static void main(String[] args) {
MapEntryEfficiencyExample mapEntryEfficiencyExample = new MapEntryEfficiencyExample();
Map<String, String> map = new HashMap<>();
map.put("Robert C. Martin", "Clean Code");
map.put("Joshua Bloch", "Effective Java");
System.out.println("Iterating Using Map.KeySet - 2 operations");
mapEntryEfficiencyExample.usingKeySet(map);
System.out.println("Iterating Using Map.Entry - 1 operation");
mapEntryEfficiencyExample.usingEntrySet(map);
}
public void usingKeySet(Map<String, String> bookMap) {
for (String key : bookMap.keySet()) {
System.out.println("key: " + key + " value: " + bookMap.get(key));
}
}
public void usingEntrySet(Map<String, String> bookMap) {
for (Map.Entry<String, String> book: bookMap.entrySet()) {
System.out.println("key: " + book.getKey() + " value: " + book.getValue());
}
}
}
@@ -0,0 +1,25 @@
package com.baeldung.map.entry;
import java.util.*;
public class MapEntryTupleExample {
public static void main(String[] args) {
Map.Entry<String, Book> tuple1;
Map.Entry<String, Book> tuple2;
Map.Entry<String, Book> tuple3;
tuple1 = new AbstractMap.SimpleEntry<>("9780134685991", new Book("Effective Java 3d Edition", "Joshua Bloch"));
tuple2 = new AbstractMap.SimpleEntry<>("9780132350884", new Book("Clean Code", "Robert C Martin"));
tuple3 = new AbstractMap.SimpleEntry<>("9780132350884", new Book("Clean Code", "Robert C Martin"));
List<Map.Entry<String, Book>> orderedTuples = new ArrayList<>();
orderedTuples.add(tuple1);
orderedTuples.add(tuple2);
orderedTuples.add(tuple3);
for (Map.Entry<String, Book> tuple : orderedTuples) {
System.out.println("key: " + tuple.getKey() + " value: " + tuple.getValue());
}
}
}
@@ -0,0 +1,33 @@
package com.baeldung.map.entry;
import org.junit.Test;
import java.util.*;
import static org.junit.Assert.assertEquals;
public class MapEntryUnitTest {
@Test
public void givenSimpleEntryList_whenAddDuplicateKey_thenDoesNotOverwriteExistingKey() {
List<Map.Entry<String, Book>> orderedTuples = new ArrayList<>();
orderedTuples.add(new AbstractMap.SimpleEntry<>("9780134685991", new Book("Effective Java 3d Edition", "Joshua Bloch")));
orderedTuples.add(new AbstractMap.SimpleEntry<>("9780132350884", new Book("Clean Code", "Robert C Martin")));
orderedTuples.add(new AbstractMap.SimpleEntry<>("9780132350884", new Book("Clean Code", "Robert C Martin")));
assertEquals(3, orderedTuples.size());
assertEquals("9780134685991", orderedTuples.get(0).getKey());
assertEquals("9780132350884", orderedTuples.get(1).getKey());
assertEquals("9780132350884", orderedTuples.get(2).getKey());
}
@Test
public void givenRegularMap_whenAddDuplicateKey_thenOverwritesExistingKey() {
Map<String, Book> entries = new HashMap<>();
entries.put("9780134685991", new Book("Effective Java 3d Edition", "Joshua Bloch"));
entries.put("9780132350884", new Book("Clean Code", "Robert C Martin"));
entries.put("9780132350884", new Book("Clean Code", "Robert C Martin"));
assertEquals(2, entries.size());
}
}
+1 -1
View File
@@ -120,7 +120,7 @@
<httpclient.version>4.5.3</httpclient.version>
<!-- <jackson.version>2.9.8</jackson.version>-->
<assertj.version>3.6.2</assertj.version>
<com.squareup.okhttp3.version>3.14.2</com.squareup.okhttp3.version>
<com.squareup.okhttp3.version>4.9.1</com.squareup.okhttp3.version>
<googleclient.version>1.23.0</googleclient.version>
<async.http.client.version>2.2.0</async.http.client.version>
<retrofit.version>2.3.0</retrofit.version>
+1
View File
@@ -6,6 +6,7 @@ This module contains articles about performance testing.
- [Performance of Java Mapping Frameworks](https://www.baeldung.com/java-performance-mapping-frameworks)
- [Performance Effects of Exceptions in Java](https://www.baeldung.com/java-exceptions-performance)
- [Is Java a Compiled or Interpreted Language?](https://www.baeldung.com/java-compiled-interpreted)
### Running

Some files were not shown because too many files have changed in this diff Show More