Merge branch 'master' into BAEL-17506

This commit is contained in:
Josh Cummings
2019-10-02 22:17:50 -06:00
committed by GitHub
888 changed files with 5633 additions and 3708 deletions
+1 -1
View File
@@ -5,6 +5,6 @@
### Relevant Articles:
- [Anonymous Classes in Java](http://www.baeldung.com/)
- [How to Delay Code Execution in Java](https://www.baeldung.com/java-delay-code-execution)
- [Run JAR Application With Command Line Arguments](https://www.baeldung.com/java-run-jar-with-arguments)
- [Run a Java Application from the Command Line](https://www.baeldung.com/java-run-jar-with-arguments)
- [Java 8 Stream skip() vs limit()](https://www.baeldung.com/java-stream-skip-vs-limit)
- [Guide to Java BiFunction Interface](https://www.baeldung.com/java-bifunction-interface)
@@ -7,3 +7,4 @@
- [Array Operations in Java](https://www.baeldung.com/java-common-array-operations)
- [Intersection Between two Integer Arrays](https://www.baeldung.com/java-array-intersection)
- [Removing an Element from an Array in Java](https://www.baeldung.com/java-array-remove-element)
- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element)
@@ -1,4 +1,4 @@
package com.baeldung.list.removefirst;
package com.baeldung.array.removefirst;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
+2 -1
View File
@@ -10,6 +10,7 @@
- [Multi-Dimensional Arrays In Java](https://www.baeldung.com/java-jagged-arrays)
- [Find Sum and Average in a Java Array](https://www.baeldung.com/java-array-sum-average)
- [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide)
- [How to Invert an Array in Java](https://www.baeldung.com/java-invert-array)
- [Read and Write User Input in Java](https://www.baeldung.com/java-console-input-output)
- [How to Reverse an Array in Java](http://www.baeldung.com/java-invert-array)
- [Sorting Arrays in Java](https://www.baeldung.com/java-sorting-arrays)
- [Checking If an Array Is Sorted in Java](https://www.baeldung.com/java-check-sorted-array)
@@ -0,0 +1,15 @@
=========
## Core Java Collections Cookbooks and Examples
### Relevant Articles:
- [Removing Elements from Java Collections](https://www.baeldung.com/java-collection-remove-elements)
- [How to Filter a Collection in Java](https://www.baeldung.com/java-collection-filtering)
- [Join and Split Arrays and Collections in Java](https://www.baeldung.com/java-join-and-split)
- [Java Combine Multiple Collections](https://www.baeldung.com/java-combine-multiple-collections)
- [Combining Different Types of Collections in Java](https://www.baeldung.com/java-combine-collections)
- [Shuffling Collections In Java](https://www.baeldung.com/java-shuffle-collection)
- [Sorting in Java](https://www.baeldung.com/java-sorting)
- [Getting the Size of an Iterable in Java](https://www.baeldung.com/java-iterable-size)
- [Java Null-Safe Streams from Collections](https://www.baeldung.com/java-null-safe-streams-from-collections)
@@ -0,0 +1,58 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-collections-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>core-java-collections-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.eclipse.collections</groupId>
<artifactId>eclipse-collections</artifactId>
<version>${eclipse.collections.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-exec</artifactId>
<version>${commons-exec.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<eclipse.collections.version>7.1.0</eclipse.collections.version>
<commons-collections4.version>4.1</commons-collections4.version>
<assertj.version>3.11.1</assertj.version>
<junit.platform.version>1.2.0</junit.platform.version>
<commons-exec.version>1.3</commons-exec.version>
</properties>
</project>
@@ -1,4 +1,4 @@
package com.baeldung.combiningcollections;
package com.baeldung.collections.combiningcollections;
import java.util.Arrays;
import java.util.stream.Stream;
@@ -1,4 +1,4 @@
package com.baeldung.combiningcollections;
package com.baeldung.collections.combiningcollections;
import java.util.ArrayList;
import java.util.Collection;
@@ -1,4 +1,4 @@
package com.baeldung.combiningcollections;
package com.baeldung.collections.combiningcollections;
import java.util.Collection;
import java.util.HashMap;
@@ -1,4 +1,4 @@
package com.baeldung.combiningcollections;
package com.baeldung.collections.combiningcollections;
import java.util.Collection;
import java.util.HashSet;
@@ -1,4 +1,4 @@
package com.baeldung.java.filtering;
package com.baeldung.collections.filtering;
import java.util.Collection;
@@ -1,4 +1,4 @@
package com.baeldung.java.filtering;
package com.baeldung.collections.filtering;
import java.util.Collection;
import java.util.function.Predicate;
@@ -1,4 +1,4 @@
package com.baeldung.java.iterable;
package com.baeldung.collections.iterablesize;
import java.util.Collection;
import java.util.stream.StreamSupport;
@@ -1,4 +1,4 @@
package com.baeldung.nullsafecollectionstreams;
package com.baeldung.collections.nullsafecollectionstreams;
import java.util.Collection;
import java.util.stream.Stream;
@@ -1,4 +1,4 @@
package com.baeldung.nullsafecollectionstreams;
package com.baeldung.collections.nullsafecollectionstreams;
import java.util.Collection;
import java.util.stream.Stream;
@@ -1,4 +1,4 @@
package com.baeldung.removal;
package com.baeldung.collections.removal;
import java.util.ArrayList;
import java.util.Collection;
@@ -1,4 +1,4 @@
package com.baeldung.removal;
package com.baeldung.collections.removal;
import java.util.ArrayList;
import java.util.Collection;
@@ -1,4 +1,4 @@
package com.baeldung.removal;
package com.baeldung.collections.removal;
import java.util.ArrayList;
import java.util.Collection;
@@ -1,4 +1,4 @@
package com.baeldung.removal;
package com.baeldung.collections.removal;
import java.util.ArrayList;
import java.util.Collection;
@@ -1,4 +1,4 @@
package com.baeldung.combiningcollections;
package com.baeldung.collections.combiningcollections;
import static org.junit.Assert.*;
import org.junit.Test;
@@ -1,4 +1,4 @@
package com.baeldung.combiningcollections;
package com.baeldung.collections.combiningcollections;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
@@ -1,4 +1,4 @@
package com.baeldung.combiningcollections;
package com.baeldung.collections.combiningcollections;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
@@ -1,5 +1,5 @@
package com.baeldung.combiningcollections;
package com.baeldung.collections.combiningcollections;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
@@ -1,4 +1,4 @@
package com.baeldung.java.filtering;
package com.baeldung.collections.filtering;
import static org.assertj.core.api.Assertions.assertThat;
@@ -1,4 +1,4 @@
package com.baeldung.java.iterable;
package com.baeldung.collections.iterablesize;
import static org.junit.Assert.assertEquals;
@@ -1,4 +1,4 @@
package org.baeldung.java.collections;
package com.baeldung.collections.joinsplit;
import java.util.ArrayList;
import java.util.Collections;
@@ -1,4 +1,4 @@
package org.baeldung.java.collections;
package com.baeldung.collections.multiplecollections;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
@@ -14,7 +14,7 @@ import java.util.stream.Stream;
import static java.util.Arrays.asList;
public class CollectionsConcatenateUnitTest {
public class CombineMultipleCollectionsUnitTest {
@Test
public void givenUsingJava8_whenConcatenatingUsingConcat_thenCorrect() {
@@ -1,4 +1,4 @@
package com.baeldung.removal;
package com.baeldung.collections.removal;
import org.junit.Before;
import org.junit.Test;
@@ -1,4 +1,4 @@
package org.baeldung.java.sorting;
package com.baeldung.collections.sorting;
public class Employee implements Comparable {
@@ -1,4 +1,4 @@
package org.baeldung.java.sorting;
package com.baeldung.collections.sorting;
import com.google.common.primitives.Ints;
import org.apache.commons.lang3.ArrayUtils;
@@ -0,0 +1,11 @@
=========
## Core Java Collections Cookbooks and Examples
### Relevant Articles:
- [Time Comparison of Arrays.sort(Object[]) and Arrays.sort(int[])](https://www.baeldung.com/arrays-sortobject-vs-sortint)
- [Java ArrayList vs Vector](https://www.baeldung.com/java-arraylist-vs-vector)
- [Differences Between HashMap and Hashtable](https://www.baeldung.com/hashmap-hashtable-differences)
- [Differences Between Collection.clear() and Collection.removeAll()](https://www.baeldung.com/java-collection-clear-vs-removeall)
- [Performance of contains() in a HashSet vs ArrayList](https://www.baeldung.com/java-hashset-arraylist-contains-performance)
- [Fail-Safe Iterator vs Fail-Fast Iterator](https://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
@@ -0,0 +1,34 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-collections-3</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-3</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${openjdk.jmh.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<openjdk.jmh.version>1.19</openjdk.jmh.version>
<assertj.version>3.11.1</assertj.version>
</properties>
</project>
@@ -1,4 +1,4 @@
package com.baeldung.performance;
package com.baeldung.collections.arraylistvsvector;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
@@ -0,0 +1,55 @@
package com.baeldung.collections.arraylistvsvector;
public class Employee {
private Long id;
private String name;
public Employee(Long id, String name) {
this.name = name;
this.id = id;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
if (!id.equals(employee.id)) return false;
return name.equals(employee.name);
}
@Override
public int hashCode() {
int result = id.hashCode();
result = 31 * result + name.hashCode();
return result;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
@@ -1,4 +1,4 @@
package com.baeldung.java.list;
package com.baeldung.collections.arraylistvsvector;
import java.util.Enumeration;
import java.util.Iterator;
@@ -1,4 +1,4 @@
package com.baeldung.performance;
package com.baeldung.collections.containsperformance;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
@@ -0,0 +1,55 @@
package com.baeldung.collections.containsperformance;
public class Employee {
private Long id;
private String name;
public Employee(Long id, String name) {
this.name = name;
this.id = id;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
if (!id.equals(employee.id)) return false;
return name.equals(employee.name);
}
@Override
public int hashCode() {
int result = id.hashCode();
result = 31 * result + name.hashCode();
return result;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
@@ -1,4 +1,4 @@
package com.baeldung.iterators;
package com.baeldung.collections.iterators;
import java.util.ArrayList;
import java.util.Iterator;
@@ -1,4 +1,4 @@
package com.baeldung.performance;
package com.baeldung.collections.sortingcomparison;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
@@ -1,4 +1,4 @@
package com.baeldung.java.sort;
package com.baeldung.collections.sortingcomparison;
import java.util.ArrayList;
import java.util.Arrays;
@@ -1,4 +1,4 @@
package com.baeldung.collection;
package com.baeldung.collections.clearvsremoveall;
import org.junit.jupiter.api.Test;
@@ -1,4 +1,4 @@
package com.baeldung.hashmapvshashtable;
package com.baeldung.collections.hashmapvshashtable;
import static org.junit.Assert.assertEquals;
@@ -1,8 +1,8 @@
package com.baeldung.iterators;
package com.baeldung.collections.iterators;
import static com.baeldung.iterators.Iterators.failFast1;
import static com.baeldung.iterators.Iterators.failFast2;
import static com.baeldung.iterators.Iterators.failSafe1;
import static com.baeldung.collections.iterators.Iterators.failFast1;
import static com.baeldung.collections.iterators.Iterators.failFast2;
import static com.baeldung.collections.iterators.Iterators.failSafe1;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@@ -11,4 +11,4 @@
- [Remove the First Element from a List](http://www.baeldung.com/java-remove-first-element-from-list)
- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java)
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
- [Remove All Occurrences of a Specific Value from a List](https://www.baeldung.com/java-remove-value-from-list)
- [Remove All Occurrences of a Specific Value from a List](https://www.baeldung.com/java-remove-value-from-list)
@@ -3,29 +3,13 @@
## Core Java Collections Cookbooks and Examples
### Relevant Articles:
- [Java Combine Multiple Collections](http://www.baeldung.com/java-combine-multiple-collections)
- [Collect a Java Stream to an Immutable Collection](http://www.baeldung.com/java-stream-immutable-collection)
- [Introduction to the Java ArrayDeque](http://www.baeldung.com/java-array-deque)
- [Getting the Size of an Iterable in Java](http://www.baeldung.com/java-iterable-size)
- [How to Filter a Collection in Java](http://www.baeldung.com/java-collection-filtering)
- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element)
- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection)
- [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table)
- [Java Null-Safe Streams from Collections](https://www.baeldung.com/java-null-safe-streams-from-collections)
- [Collect a Java Stream to an Immutable Collection](https://www.baeldung.com/java-stream-immutable-collection)
- [Introduction to the Java ArrayDeque](https://www.baeldung.com/java-array-deque)
- [An Introduction to Java.util.Hashtable Class](https://www.baeldung.com/java-hash-table)
- [Thread Safe LIFO Data Structure Implementations](https://www.baeldung.com/java-lifo-thread-safe)
- [Differences Between Collection.clear() and Collection.removeAll()](https://www.baeldung.com/java-collection-clear-vs-removeall)
- [Performance of contains() in a HashSet vs ArrayList](https://www.baeldung.com/java-hashset-arraylist-contains-performance)
- [Time Complexity of Java Collections](https://www.baeldung.com/java-collections-complexity)
- [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream)
- [An Introduction to Synchronized Java Collections](https://www.baeldung.com/java-synchronized-collections)
- [Removing Elements from Java Collections](https://www.baeldung.com/java-collection-remove-elements)
- [Combining Different Types of Collections in Java](https://www.baeldung.com/java-combine-collections)
- [Sorting in Java](http://www.baeldung.com/java-sorting)
- [Join and Split Arrays and Collections in Java](http://www.baeldung.com/java-join-and-split)
- [A Guide to EnumMap](https://www.baeldung.com/java-enum-map)
- [A Guide to Iterator in Java](http://www.baeldung.com/java-iterator)
- [Differences Between HashMap and Hashtable](https://www.baeldung.com/hashmap-hashtable-differences)
- [Java ArrayList vs Vector](https://www.baeldung.com/java-arraylist-vs-vector)
- [A Guide to Iterator in Java](https://www.baeldung.com/java-iterator)
- [Defining a Char Stack in Java](https://www.baeldung.com/java-char-stack)
- [Time Comparison of Arrays.sort(Object[]) and Arrays.sort(int[])](https://www.baeldung.com/arrays-sortobject-vs-sortint)
- [Guide to the Java Queue Interface](https://www.baeldung.com/java-queue)
- [An Introduction to Synchronized Java Collections](https://www.baeldung.com/java-synchronized-collections)
@@ -14,33 +14,12 @@
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.collections</groupId>
<artifactId>eclipse-collections</artifactId>
<version>${eclipse.collections.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
@@ -51,11 +30,6 @@
<artifactId>jmh-generator-annprocess</artifactId>
<version>${openjdk.jmh.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-exec</artifactId>
<version>${commons-exec.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
@@ -66,13 +40,6 @@
<properties>
<openjdk.jmh.version>1.19</openjdk.jmh.version>
<junit.platform.version>1.2.0</junit.platform.version>
<commons-lang3.version>3.8.1</commons-lang3.version>
<commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version>
<avaitility.version>1.7.0</avaitility.version>
<assertj.version>3.11.1</assertj.version>
<eclipse.collections.version>7.1.0</eclipse.collections.version>
<commons-exec.version>1.3</commons-exec.version>
</properties>
</project>
@@ -1,4 +1,4 @@
package com.baeldung.synchronizedcollections.application;
package com.baeldung.synchronizedcollections;
import java.util.Arrays;
import java.util.Collections;
@@ -1,83 +0,0 @@
package com.baeldung.java.collections;
import org.junit.Test;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
public class ConcurrentModificationExceptionUnitTest {
@Test
public void changingContentWithSetDoesNotThrowConcurrentModificationException() throws Exception {
ArrayList<Object> array = new ArrayList<>(asList(0, "one", 2, "three"));
for (Object item : array) {
array.set(3, 3);
}
}
@Test
public void removingElementUsingIteratorAPI() throws Exception {
List<String> originalList = new ArrayList<>(asList("zero", "one", "two", "three"));
Iterator<String> iterator = originalList.iterator();
while (iterator.hasNext()) {
String next = iterator.next();
if (Objects.equals(next, "one")) iterator.remove();
}
assertEquals(originalList, asList("zero", "two", "three"));
}
@Test
public void modifyingContentAndIteratingUsingListIteratorAPI() throws Exception {
List<String> originalList = new ArrayList<>(asList("zero", "one", "two", "three"));
ListIterator<String> iterator = originalList.listIterator();
while (iterator.hasNext()) {
String next = iterator.next();
if (Objects.equals(next, "one")) {
iterator.set("another");
}
if (Objects.equals(next, "two")) {
iterator.remove();
}
if (Objects.equals(next, "three")) {
iterator.add("four");
}
}
assertEquals(originalList, asList("zero", "another", "three", "four"));
}
@Test
public void removingElementUsingCopyAndListAPI() throws Exception {
List<String> originalList = new ArrayList<>(asList("zero", "one", "two", "three"));
List<String> listCopy = new ArrayList<>(originalList);
for (String next : listCopy) {
if (Objects.equals(next, "one")) originalList.remove(originalList.indexOf(next) - 1);
}
assertEquals(originalList, asList("one", "two", "three"));
}
@Test
public void copyOnWriteList() throws Exception {
List<String> originalList = new CopyOnWriteArrayList<>(asList("zero", "one", "two", "three"));
for (String next : originalList) {
if (Objects.equals(next, "one")) originalList.remove(originalList.indexOf(next) - 1);
}
assertEquals(originalList, asList("one", "two", "three"));
}
}
@@ -1,4 +1,4 @@
package com.baeldung.synchronizedcollections.test;
package com.baeldung.synchronizedcollections;
import java.util.ArrayList;
import java.util.Arrays;
@@ -1,4 +1,4 @@
package com.baeldung.synchronizedcollections.test;
package com.baeldung.synchronizedcollections;
import java.util.ArrayList;
import java.util.Arrays;
@@ -1,4 +1,4 @@
package com.baeldung.synchronizedcollections.test;
package com.baeldung.synchronizedcollections;
import java.util.Collections;
import java.util.HashMap;
@@ -1,4 +1,4 @@
package com.baeldung.synchronizedcollections.test;
package com.baeldung.synchronizedcollections;
import java.util.Arrays;
import java.util.Collections;
@@ -1,4 +1,4 @@
package com.baeldung.synchronizedcollections.test;
package com.baeldung.synchronizedcollections;
import java.util.Collections;
import java.util.Map;
@@ -1,4 +1,4 @@
package com.baeldung.synchronizedcollections.test;
package com.baeldung.synchronizedcollections;
import java.util.Arrays;
import java.util.Collections;
@@ -1,3 +0,0 @@
### Relevant Articles:
- [Join and Split Arrays and Collections in Java](http://www.baeldung.com/java-join-and-split)
- [Introduction to Java Servlets](http://www.baeldung.com/intro-to-servlets)
@@ -1,8 +1,13 @@
## Relevant Articles:
## Core Java Exceptions
- [Will an Error Be Caught by Catch Block in Java?](https://www.baeldung.com/java-error-catch)
- [Java Global Exception Handler](http://www.baeldung.com/java-global-exception-handler)
- [Common Java Exceptions](http://www.baeldung.com/java-common-exceptions)
- [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception)
- [How to Find an Exceptions Root Cause in Java](https://www.baeldung.com/java-exception-root-cause)
- [Java Try with Resources](https://www.baeldung.com/java-try-with-resources)
This module contains articles about core java exceptions
### Relevant articles:
- [Chained Exceptions in Java](https://www.baeldung.com/java-chained-exceptions)
- [ClassNotFoundException vs NoClassDefFoundError](https://www.baeldung.com/java-classnotfoundexception-and-noclassdeffounderror)
- [Create a Custom Exception in Java](https://www.baeldung.com/java-new-custom-exception)
- [Exception Handling in Java](https://www.baeldung.com/java-exceptions)
- [Differences Between Final, Finally and Finalize in Java](https://www.baeldung.com/java-final-finally-finalize)
- [Difference Between Throw and Throws in Java](https://www.baeldung.com/java-throw-throws)
- [“Sneaky Throws” in Java](https://www.baeldung.com/java-sneaky-throws)
- [The StackOverflowError in Java](https://www.baeldung.com/java-stack-overflow-error)
+41 -50
View File
@@ -1,55 +1,46 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.exception.numberformat</groupId>
<artifactId>core-java-exceptions</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>core-java-exceptions</name>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<groupId>com.baeldung.exceptions</groupId>
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-exceptions</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-exceptions</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator-annprocess.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<dependencies>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>${javax.mail.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<commons-lang3.version>3.9</commons-lang3.version>
<jmh-core.version>1.19</jmh-core.version>
<assertj-core.version>3.10.0</assertj-core.version>
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>
</properties>
<properties>
<javax.mail.version>1.5.0-b01</javax.mail.version>
<!-- testing -->
<assertj-core.version>3.10.0</assertj-core.version>
</properties>
</project>
</project>
@@ -1,20 +0,0 @@
package com.baeldung.exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Arithmetic {
private static Logger LOGGER = LoggerFactory.getLogger(Arithmetic.class);
public static void main(String[] args) {
try {
int result = 30 / 0; // Trying to divide by zero
} catch (ArithmeticException e) {
LOGGER.error("ArithmeticException caught!");
}
}
}
@@ -1,24 +0,0 @@
package com.baeldung.exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ArrayIndexOutOfBounds {
private static Logger LOGGER = LoggerFactory.getLogger(ArrayIndexOutOfBounds.class);
public static void main(String[] args) {
int[] nums = new int[] { 1, 2, 3 };
try {
int numFromNegativeIndex = nums[-1]; // Trying to access at negative index
int numFromGreaterIndex = nums[4]; // Trying to access at greater index
int numFromLengthIndex = nums[3]; // Trying to access at index equal to size of the array
} catch (ArrayIndexOutOfBoundsException e) {
LOGGER.error("ArrayIndexOutOfBoundsException caught");
}
}
}
@@ -1,43 +0,0 @@
package com.baeldung.exceptions;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class CheckedUncheckedExceptions {
public static void checkedExceptionWithThrows() throws FileNotFoundException {
File file = new File("not_existing_file.txt");
FileInputStream stream = new FileInputStream(file);
}
public static void checkedExceptionWithTryCatch() {
File file = new File("not_existing_file.txt");
try {
FileInputStream stream = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static int divideByZero() {
int numerator = 1;
int denominator = 0;
return numerator / denominator;
}
public static void checkFile(String fileName) throws IncorrectFileNameException {
if (fileName == null || fileName.isEmpty()) {
throw new NullOrEmptyException("The filename is null.");
}
if (!isCorrectFileName(fileName)) {
throw new IncorrectFileNameException("Incorrect filename : " + fileName);
}
}
private static boolean isCorrectFileName(String fileName) {
if (fileName.equals("wrongFileName.txt"))
return false;
else
return true;
}
}
@@ -1,36 +0,0 @@
package com.baeldung.exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class Animal {
}
class Dog extends Animal {
}
class Lion extends Animal {
}
public class ClassCast {
private static Logger LOGGER = LoggerFactory.getLogger(ClassCast.class);
public static void main(String[] args) {
try {
Animal animalOne = new Dog(); // At runtime the instance is dog
Dog bruno = (Dog) animalOne; // Downcasting
Animal animalTwo = new Lion(); // At runtime the instance is animal
Dog tommy = (Dog) animalTwo; // Downcasting
} catch (ClassCastException e) {
LOGGER.error("ClassCastException caught!");
}
}
}
@@ -1,25 +0,0 @@
package com.baeldung.exceptions;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FileNotFound {
private static Logger LOGGER = LoggerFactory.getLogger(FileNotFound.class);
public static void main(String[] args) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(new File("/invalid/file/location")));
} catch (FileNotFoundException e) {
LOGGER.error("FileNotFoundException caught!");
}
}
}
@@ -1,28 +0,0 @@
package com.baeldung.exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GlobalExceptionHandler {
public static void main(String[] args) {
Handler globalExceptionHandler = new Handler();
Thread.setDefaultUncaughtExceptionHandler(globalExceptionHandler);
new GlobalExceptionHandler().performArithmeticOperation(10, 0);
}
public int performArithmeticOperation(int num1, int num2) {
return num1/num2;
}
}
class Handler implements Thread.UncaughtExceptionHandler {
private static Logger LOGGER = LoggerFactory.getLogger(Handler.class);
public void uncaughtException(Thread t, Throwable e) {
LOGGER.info("Unhandled exception caught!");
}
}
@@ -1,18 +0,0 @@
package com.baeldung.exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class IllegalArgument {
private static Logger LOGGER = LoggerFactory.getLogger(IllegalArgument.class);
public static void main(String[] args) {
try {
Thread.sleep(-1000);
} catch (InterruptedException e) {
LOGGER.error("IllegalArgumentException caught!");
}
}
}
@@ -1,32 +0,0 @@
package com.baeldung.exceptions;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class IllegalState {
private static Logger LOGGER = LoggerFactory.getLogger(IllegalState.class);
public static void main(String[] args) {
List<Integer> intList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
intList.add(i);
}
Iterator<Integer> intListIterator = intList.iterator(); // Initialized with index at -1
try {
intListIterator.remove(); // IllegalStateException
} catch (IllegalStateException e) {
LOGGER.error("IllegalStateException caught!");
}
}
}
@@ -1,13 +0,0 @@
package com.baeldung.exceptions;
public class IncorrectFileNameException extends Exception {
private static final long serialVersionUID = 1L;
public IncorrectFileNameException(String errorMessage) {
super(errorMessage);
}
public IncorrectFileNameException(String errorMessage, Throwable thr) {
super(errorMessage, thr);
}
}
@@ -1,28 +0,0 @@
package com.baeldung.exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class ChildThread extends Thread {
private static Logger LOGGER = LoggerFactory.getLogger(ChildThread.class);
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
LOGGER.error("InterruptedException caught!");
}
}
}
public class InterruptedExceptionExample {
public static void main(String[] args) throws InterruptedException {
ChildThread childThread = new ChildThread();
childThread.start();
childThread.interrupt();
}
}
@@ -1,25 +0,0 @@
package com.baeldung.exceptions;
import java.net.MalformedURLException;
import java.net.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MalformedURL {
private static Logger LOGGER = LoggerFactory.getLogger(MalformedURL.class);
public static void main(String[] args) {
URL baeldungURL = null;
try {
baeldungURL = new URL("malformedurl");
} catch (MalformedURLException e) {
LOGGER.error("MalformedURLException caught!");
}
}
}
@@ -1,14 +0,0 @@
package com.baeldung.exceptions;
public class NullOrEmptyException extends RuntimeException {
private static final long serialVersionUID = 1L;
public NullOrEmptyException(String errorMessage) {
super(errorMessage);
}
public NullOrEmptyException(String errorMessage, Throwable thr) {
super(errorMessage, thr);
}
}
@@ -1,36 +0,0 @@
package com.baeldung.exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NullPointer {
private static Logger LOGGER = LoggerFactory.getLogger(NullPointer.class);
public static void main(String[] args) {
Person personObj = null;
try {
String name = personObj.personName; // Accessing the field of a null object
personObj.personName = "Jon Doe"; // Modifying the field of a null object
} catch (NullPointerException e) {
LOGGER.error("NullPointerException caught!");
}
}
}
class Person {
public String personName;
public String getPersonName() {
return personName;
}
public void setPersonName(String personName) {
this.personName = personName;
}
}
@@ -1,23 +0,0 @@
package com.baeldung.exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NumberFormat {
private static Logger LOGGER = LoggerFactory.getLogger(NumberFormat.class);
public static void main(String[] args) {
String str1 = "100ABCD";
try {
int x = Integer.parseInt(str1); // Converting string with inappropriate format
int y = Integer.valueOf(str1);
} catch (NumberFormatException e) {
LOGGER.error("NumberFormatException caught!");
}
}
}
@@ -1,25 +0,0 @@
package com.baeldung.exceptions;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ParseExceptionExample {
private static Logger LOGGER = LoggerFactory.getLogger(ParseExceptionExample.class);
public static void main(String[] args) {
DateFormat format = new SimpleDateFormat("MM, dd, yyyy");
try {
format.parse("01, , 2010");
} catch (ParseException e) {
LOGGER.error("ParseException caught!");
}
}
}
@@ -1,98 +0,0 @@
package com.baeldung.exceptions;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeParseException;
import java.util.Objects;
/**
* Utility class to find root cause exceptions.
*/
public class RootCauseFinder {
private RootCauseFinder() {
}
public static Throwable findCauseUsingPlainJava(Throwable throwable) {
Objects.requireNonNull(throwable);
Throwable rootCause = throwable;
while (rootCause.getCause() != null && rootCause.getCause() != rootCause) {
rootCause = rootCause.getCause();
}
return rootCause;
}
/**
* Calculates the age of a person from a given date.
*/
static class AgeCalculator {
private AgeCalculator() {
}
public static int calculateAge(String birthDate) {
if (birthDate == null || birthDate.isEmpty()) {
throw new IllegalArgumentException();
}
try {
return Period
.between(parseDate(birthDate), LocalDate.now())
.getYears();
} catch (DateParseException ex) {
throw new CalculationException(ex);
}
}
private static LocalDate parseDate(String birthDateAsString) {
LocalDate birthDate;
try {
birthDate = LocalDate.parse(birthDateAsString);
} catch (DateTimeParseException ex) {
throw new InvalidFormatException(birthDateAsString, ex);
}
if (birthDate.isAfter(LocalDate.now())) {
throw new DateOutOfRangeException(birthDateAsString);
}
return birthDate;
}
}
static class CalculationException extends RuntimeException {
CalculationException(DateParseException ex) {
super(ex);
}
}
static class DateParseException extends RuntimeException {
DateParseException(String input) {
super(input);
}
DateParseException(String input, Throwable thr) {
super(input, thr);
}
}
static class InvalidFormatException extends DateParseException {
InvalidFormatException(String input, Throwable thr) {
super("Invalid date format: " + input, thr);
}
}
static class DateOutOfRangeException extends DateParseException {
DateOutOfRangeException(String date) {
super("Date out of range: " + date);
}
}
}
@@ -1,30 +0,0 @@
package com.baeldung.exceptions;
import org.apache.commons.lang3.exception.ExceptionUtils;
import java.io.PrintWriter;
import java.io.StringWriter;
public class StackTraceToString {
public static void main(String[] args) {
// Convert a StackTrace to String using core java
try {
throw new NullPointerException();
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
System.out.println(sw.toString());
}
// Convert a StackTrace to String using Apache Commons
try {
throw new IndexOutOfBoundsException();
} catch (Exception e) {
System.out.println(ExceptionUtils.getStackTrace(e));
}
}
}
@@ -1,23 +0,0 @@
package com.baeldung.exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StringIndexOutOfBounds {
private static Logger LOGGER = LoggerFactory.getLogger(StringIndexOutOfBounds.class);
public static void main(String[] args) {
String str = "Hello World";
try {
char charAtNegativeIndex = str.charAt(-1); // Trying to access at negative index
char charAtLengthIndex = str.charAt(11); // Trying to access at index equal to size of the string
} catch (StringIndexOutOfBoundsException e) {
LOGGER.error("StringIndexOutOfBoundsException caught");
}
}
}
@@ -1,9 +1,9 @@
package com.baeldung.chainedexception;
package com.baeldung.exceptions.chainedexception;
import com.baeldung.chainedexception.exceptions.GirlFriendOfManagerUpsetException;
import com.baeldung.chainedexception.exceptions.ManagerUpsetException;
import com.baeldung.chainedexception.exceptions.NoLeaveGrantedException;
import com.baeldung.chainedexception.exceptions.TeamLeadUpsetException;
import com.baeldung.exceptions.chainedexception.exceptions.GirlFriendOfManagerUpsetException;
import com.baeldung.exceptions.chainedexception.exceptions.ManagerUpsetException;
import com.baeldung.exceptions.chainedexception.exceptions.NoLeaveGrantedException;
import com.baeldung.exceptions.chainedexception.exceptions.TeamLeadUpsetException;
public class LogWithChain {
@@ -1,9 +1,9 @@
package com.baeldung.chainedexception;
package com.baeldung.exceptions.chainedexception;
import com.baeldung.chainedexception.exceptions.GirlFriendOfManagerUpsetException;
import com.baeldung.chainedexception.exceptions.ManagerUpsetException;
import com.baeldung.chainedexception.exceptions.NoLeaveGrantedException;
import com.baeldung.chainedexception.exceptions.TeamLeadUpsetException;
import com.baeldung.exceptions.chainedexception.exceptions.GirlFriendOfManagerUpsetException;
import com.baeldung.exceptions.chainedexception.exceptions.ManagerUpsetException;
import com.baeldung.exceptions.chainedexception.exceptions.NoLeaveGrantedException;
import com.baeldung.exceptions.chainedexception.exceptions.TeamLeadUpsetException;
public class LogWithoutChain {
@@ -1,4 +1,4 @@
package com.baeldung.chainedexception.exceptions;
package com.baeldung.exceptions.chainedexception.exceptions;
public class GirlFriendOfManagerUpsetException extends Exception {
@@ -1,4 +1,4 @@
package com.baeldung.chainedexception.exceptions;
package com.baeldung.exceptions.chainedexception.exceptions;
public class ManagerUpsetException extends Exception {
@@ -1,4 +1,4 @@
package com.baeldung.chainedexception.exceptions;
package com.baeldung.exceptions.chainedexception.exceptions;
public class NoLeaveGrantedException extends Exception {
@@ -1,4 +1,4 @@
package com.baeldung.chainedexception.exceptions;
package com.baeldung.exceptions.chainedexception.exceptions;
public class TeamLeadUpsetException extends Exception {
@@ -1,4 +1,4 @@
package com.baeldung.customexception;
package com.baeldung.exceptions.customexception;
import java.io.File;
import java.io.FileNotFoundException;
@@ -1,4 +1,4 @@
package com.baeldung.customexception;
package com.baeldung.exceptions.customexception;
public class IncorrectFileExtensionException extends RuntimeException{
private static final long serialVersionUID = 1L;
@@ -1,4 +1,4 @@
package com.baeldung.customexception;
package com.baeldung.exceptions.customexception;
public class IncorrectFileNameException extends Exception {
private static final long serialVersionUID = 1L;
@@ -1,4 +1,4 @@
package com.baeldung.exceptionhandling;
package com.baeldung.exceptions.exceptionhandling;
import java.io.File;
import java.io.FileNotFoundException;
@@ -0,0 +1,5 @@
package com.baeldung.exceptions.exceptionhandling;
public class MyException extends Throwable {
}
@@ -1,4 +1,4 @@
package com.baeldung.exceptionhandling;
package com.baeldung.exceptions.exceptionhandling;
public class Player {
@@ -1,4 +1,4 @@
package com.baeldung.exceptionhandling;
package com.baeldung.exceptions.exceptionhandling;
import java.io.IOException;
@@ -1,4 +1,4 @@
package com.baeldung.exceptionhandling;
package com.baeldung.exceptions.exceptionhandling;
public class PlayerScoreException extends Exception {
@@ -1,4 +1,4 @@
package com.baeldung.exceptionhandling;
package com.baeldung.exceptions.exceptionhandling;
public class TimeoutException extends Exception {
@@ -1,4 +1,4 @@
package com.baeldung.keywords.finalize;
package com.baeldung.exceptions.keywords.finalize;
public class FinalizeObject {
@@ -1,4 +1,4 @@
package com.baeldung.keywords.finalkeyword;
package com.baeldung.exceptions.keywords.finalkeyword;
public final class Child extends Parent {

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