Merge pull request #5649 from rozagerardo/geroza/BAEL-9549_reduce-articles-in-core-java
[BAEL-9549] reduce core-java module migrating code to core-java-lang and core-java-arrays
This commit is contained in:
@@ -6,101 +6,56 @@
|
||||
- [Java Timer](http://www.baeldung.com/java-timer-and-timertask)
|
||||
- [How to Run a Shell Command in Java](http://www.baeldung.com/run-shell-command-in-java)
|
||||
- [MD5 Hashing in Java](http://www.baeldung.com/java-md5)
|
||||
- [Guide to Java Reflection](http://www.baeldung.com/java-reflection)
|
||||
- [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets)
|
||||
- [Java – Try with Resources](http://www.baeldung.com/java-try-with-resources)
|
||||
- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join)
|
||||
- [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java)
|
||||
- [Introduction to Java Generics](http://www.baeldung.com/java-generics)
|
||||
- [Generate equals() and hashCode() with Eclipse](http://www.baeldung.com/java-eclipse-equals-and-hashcode)
|
||||
- [A Guide To Java Regular Expressions API](http://www.baeldung.com/regular-expressions-java)
|
||||
- [Sorting in Java](http://www.baeldung.com/java-sorting)
|
||||
- [Getting Started with Java Properties](http://www.baeldung.com/java-properties)
|
||||
- [Grep in Java](http://www.baeldung.com/grep-in-java)
|
||||
- [Pattern Search with Grep in Java](http://www.baeldung.com/grep-in-java)
|
||||
- [URL Encoding and Decoding in Java](http://www.baeldung.com/java-url-encoding-decoding)
|
||||
- [The Basics of Java Generics](http://www.baeldung.com/java-generics)
|
||||
- [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven)
|
||||
- [How to Design a Genetic Algorithm in Java](http://www.baeldung.com/java-genetic-algorithm)
|
||||
- [Basic Introduction to JMX](http://www.baeldung.com/java-management-extensions)
|
||||
- [AWS Lambda With Java](http://www.baeldung.com/java-aws-lambda)
|
||||
- [Introduction to Nashorn](http://www.baeldung.com/java-nashorn)
|
||||
- [Chained Exceptions in Java](http://www.baeldung.com/java-chained-exceptions)
|
||||
- [Java Primitive Conversions](http://www.baeldung.com/java-primitive-conversions)
|
||||
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
|
||||
- [JVM Log Forging](http://www.baeldung.com/jvm-log-forging)
|
||||
- [Guide to sun.misc.Unsafe](http://www.baeldung.com/java-unsafe)
|
||||
- [How to Perform a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request)
|
||||
- [Call Methods at Runtime Using Java Reflection](http://www.baeldung.com/java-method-reflection)
|
||||
- [How to Add a Single Element to a Stream](http://www.baeldung.com/java-stream-append-prepend)
|
||||
- [Iterating Over Enum Values in Java](http://www.baeldung.com/java-enum-iteration)
|
||||
- [Kotlin Java Interoperability](http://www.baeldung.com/kotlin-java-interoperability)
|
||||
- [Changing Annotation Parameters At Runtime](http://www.baeldung.com/java-reflection-change-annotation-params)
|
||||
- [How to Find all Getters Returning Null](http://www.baeldung.com/java-getters-returning-null)
|
||||
- [Changing the Order in a Sum Operation Can Produce Different Results?](http://www.baeldung.com/java-floating-point-sum-order)
|
||||
- [How to Get a Name of a Method Being Executed?](http://www.baeldung.com/java-name-of-executing-method)
|
||||
- [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies)
|
||||
- [How to Copy an Array in Java](http://www.baeldung.com/java-array-copy)
|
||||
- [Converting a Stack Trace to a String in Java](http://www.baeldung.com/java-stacktrace-to-string)
|
||||
- [Java Double Brace Initialization](http://www.baeldung.com/java-double-brace-initialization)
|
||||
- [The StackOverflowError in Java](http://www.baeldung.com/java-stack-overflow-error)
|
||||
- [Introduction to Java Serialization](http://www.baeldung.com/java-serialization)
|
||||
- [ClassNotFoundException vs NoClassDefFoundError](http://www.baeldung.com/java-classnotfoundexception-and-noclassdeffounderror)
|
||||
- [Guide to UUID in Java](http://www.baeldung.com/java-uuid)
|
||||
- [Guide to Escaping Characters in Java RegExps](http://www.baeldung.com/java-regexp-escape-char)
|
||||
- [Guide to hashCode() in Java](http://www.baeldung.com/java-hashcode)
|
||||
- [Difference between URL and URI](http://www.baeldung.com/java-url-vs-uri)
|
||||
- [Broadcasting and Multicasting in Java](http://www.baeldung.com/java-broadcast-multicast)
|
||||
- [Period and Duration in Java](http://www.baeldung.com/java-period-duration)
|
||||
- [Guide to the Diamond Operator in Java](http://www.baeldung.com/java-diamond-operator)
|
||||
- [“Sneaky Throws” in Java](http://www.baeldung.com/java-sneaky-throws)
|
||||
- [OutOfMemoryError: GC Overhead Limit Exceeded](http://www.baeldung.com/java-gc-overhead-limit-exceeded)
|
||||
- [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin)
|
||||
- [A Guide to the Static Keyword in Java](http://www.baeldung.com/java-static)
|
||||
- [Initializing Arrays in Java](http://www.baeldung.com/java-initialize-array)
|
||||
- [Quick Example - Comparator vs Comparable in Java](http://www.baeldung.com/java-comparator-comparable)
|
||||
- [Quick Guide to Java Stack](http://www.baeldung.com/java-stack)
|
||||
- [The Java continue and break Keywords](http://www.baeldung.com/java-continue-and-break)
|
||||
- [Guide to java.util.Formatter](http://www.baeldung.com/java-string-formatter)
|
||||
- [Check if a Java Array Contains a Value](http://www.baeldung.com/java-array-contains-value)
|
||||
- [How to Invert an Array in Java](http://www.baeldung.com/java-invert-array)
|
||||
- [Guide to the Cipher Class](http://www.baeldung.com/java-cipher-class)
|
||||
- [A Guide to Java Initialization](http://www.baeldung.com/java-initialization)
|
||||
- [Implementing a Binary Tree in Java](http://www.baeldung.com/java-binary-tree)
|
||||
- [A Guide to ThreadLocalRandom in Java](http://www.baeldung.com/java-thread-local-random)
|
||||
- [Nested Classes in Java](http://www.baeldung.com/java-nested-classes)
|
||||
- [A Guide to Java Loops](http://www.baeldung.com/java-loops)
|
||||
- [Varargs in Java](http://www.baeldung.com/java-varargs)
|
||||
- [A Guide to Inner Interfaces in Java](http://www.baeldung.com/java-inner-interfaces)
|
||||
- [Polymorphism in Java](http://www.baeldung.com/java-polymorphism)
|
||||
- [Recursion In Java](http://www.baeldung.com/java-recursion)
|
||||
- [A Guide to the finalize Method in Java](http://www.baeldung.com/java-finalize)
|
||||
- [Compiling Java *.class Files with javac](http://www.baeldung.com/javac)
|
||||
- [Method Overloading and Overriding in Java](http://www.baeldung.com/java-method-overload-override)
|
||||
- [Guide to ThreadLocalRandom in Java](http://www.baeldung.com/java-thread-local-random)
|
||||
- [A Guide to Iterator in Java](http://www.baeldung.com/java-iterator)
|
||||
- [The Trie Data Structure in Java](http://www.baeldung.com/trie-java)
|
||||
- [Introduction to Javadoc](http://www.baeldung.com/javadoc)
|
||||
- [How to Make a Deep Copy of an Object in Java](http://www.baeldung.com/java-deep-copy)
|
||||
- [Guide to Inheritance in Java](http://www.baeldung.com/java-inheritance)
|
||||
- [Guide to Externalizable Interface in Java](http://www.baeldung.com/java-externalizable)
|
||||
- [Object Type Casting in Java](http://www.baeldung.com/java-type-casting)
|
||||
- [A Practical Guide to DecimalFormat](http://www.baeldung.com/java-decimalformat)
|
||||
- [How to Detect the OS Using Java](http://www.baeldung.com/java-detect-os)
|
||||
- [ASCII Art in Java](http://www.baeldung.com/ascii-art-in-java)
|
||||
- [Inheritance and Composition (Is-a vs Has-a relationship) in Java](http://www.baeldung.com/java-inheritance-composition)
|
||||
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
|
||||
- [The "final" Keyword in Java](http://www.baeldung.com/java-final)
|
||||
- [What is the serialVersionUID?](http://www.baeldung.com/java-serial-version-uid)
|
||||
- [A Guide To UDP In Java](http://www.baeldung.com/udp-in-java)
|
||||
- [A Guide to the Java LinkedList](http://www.baeldung.com/java-linkedlist)
|
||||
- [A Guide to Java Enums](http://www.baeldung.com/a-guide-to-java-enums)
|
||||
- [A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle)
|
||||
- [Quick Guide to java.lang.System](http://www.baeldung.com/java-lang-system)
|
||||
- [Class Loaders in Java](http://www.baeldung.com/java-classloaders)
|
||||
- [Find Sum and Average in a Java Array](http://www.baeldung.com/java-array-sum-average)
|
||||
- [Java List UnsupportedOperationException](http://www.baeldung.com/java-list-unsupported-operation-exception)
|
||||
- [Type Erasure in Java Explained](http://www.baeldung.com/java-type-erasure)
|
||||
- [Join and Split Arrays and Collections in Java](http://www.baeldung.com/java-join-and-split)
|
||||
- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
|
||||
- [Sending Emails with Java](http://www.baeldung.com/java-email)
|
||||
@@ -108,12 +63,6 @@
|
||||
- [Java KeyStore API](http://www.baeldung.com/java-keystore)
|
||||
- [Double-Checked Locking with Singleton](http://www.baeldung.com/java-singleton-double-checked-locking)
|
||||
- [Guide to Java Clock Class](http://www.baeldung.com/java-clock)
|
||||
- [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java)
|
||||
- [Using Java Assertions](http://www.baeldung.com/java-assert)
|
||||
- [Pass-By-Value as a Parameter Passing Mechanism in Java](http://www.baeldung.com/java-pass-by-value-or-pass-by-reference)
|
||||
- [Variable and Method Hiding in Java](http://www.baeldung.com/java-variable-method-hiding)
|
||||
- [Access Modifiers in Java](http://www.baeldung.com/java-access-modifiers)
|
||||
- [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java)
|
||||
- [Introduction to Creational Design Patterns](http://www.baeldung.com/creational-design-patterns)
|
||||
- [Proxy, Decorator, Adapter and Bridge Patterns](http://www.baeldung.com/java-structural-design-patterns)
|
||||
- [Singletons in Java](http://www.baeldung.com/java-singleton)
|
||||
@@ -121,42 +70,26 @@
|
||||
- [The Observer Pattern in Java](http://www.baeldung.com/java-observer-pattern)
|
||||
- [Service Locator Pattern](http://www.baeldung.com/java-service-locator-pattern)
|
||||
- [The Thread.join() Method in Java](http://www.baeldung.com/java-thread-join)
|
||||
- [Guide to the super Java Keyword](http://www.baeldung.com/java-super)
|
||||
- [Guide to the this Java Keyword](http://www.baeldung.com/java-this)
|
||||
- [Jagged Arrays In Java](http://www.baeldung.com/java-jagged-arrays)
|
||||
- [Importance of Main Manifest Attribute in a Self-Executing JAR](http://www.baeldung.com/java-jar-executable-manifest-main-class)
|
||||
- [How to Get the File Extension of a File in Java](http://www.baeldung.com/java-file-extension)
|
||||
- [Immutable Objects in Java](http://www.baeldung.com/java-immutable-object)
|
||||
- [Console I/O in Java](http://www.baeldung.com/java-console-input-output)
|
||||
- [Guide to the java.util.Arrays Class](http://www.baeldung.com/java-util-arrays)
|
||||
- [Create a Custom Exception in Java](http://www.baeldung.com/java-new-custom-exception)
|
||||
- [Java Global Exception Handler](http://www.baeldung.com/java-global-exception-handler)
|
||||
- [Encrypting and Decrypting Files in Java](http://www.baeldung.com/java-cipher-input-output-stream)
|
||||
- [How to Get the Size of an Object in Java](http://www.baeldung.com/java-size-of-object)
|
||||
- [Exception Handling in Java](http://www.baeldung.com/java-exceptions)
|
||||
- [Guide to Java Instrumentation](http://www.baeldung.com/java-instrumentation)
|
||||
- [Getting a File’s Mime Type in Java](http://www.baeldung.com/java-file-mime-type)
|
||||
- [Common Java Exceptions](http://www.baeldung.com/java-common-exceptions)
|
||||
- [Java Constructors vs Static Factory Methods](https://www.baeldung.com/java-constructors-vs-static-factory-methods)
|
||||
- [Differences Between Final, Finally and Finalize in Java](https://www.baeldung.com/java-final-finally-finalize)
|
||||
- [Static and Dynamic Binding in Java](https://www.baeldung.com/java-static-dynamic-binding)
|
||||
- [Java List Initialization in One Line](https://www.baeldung.com/java-init-list-one-line)
|
||||
- [Difference Between Throw and Throws in Java](https://www.baeldung.com/java-throw-throws)
|
||||
- [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist)
|
||||
- [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception)
|
||||
- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string)
|
||||
- [Synthetic Constructs in Java](https://www.baeldung.com/java-synthetic)
|
||||
- [Calculating the nth Root in Java](https://www.baeldung.com/java-nth-root)
|
||||
- [Convert Double to String, Removing Decimal Places](https://www.baeldung.com/java-double-to-string)
|
||||
- [Different Ways to Capture Java Heap Dumps](https://www.baeldung.com/java-heap-dump-capture)
|
||||
- [How to Separate Double into Integer and Decimal Parts](https://www.baeldung.com/java-separate-double-into-integer-decimal-parts)
|
||||
- [ZoneOffset in Java](https://www.baeldung.com/java-zone-offset)
|
||||
- [Hashing a Password in Java](https://www.baeldung.com/java-password-hashing)
|
||||
- [Java Switch Statement](https://www.baeldung.com/java-switch)
|
||||
- [The Modulo Operator in Java](https://www.baeldung.com/modulo-java)
|
||||
- [Ternary Operator In Java](https://www.baeldung.com/java-ternary-operator)
|
||||
- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)
|
||||
- [Understanding Memory Leaks in Java](https://www.baeldung.com/java-memory-leaks)
|
||||
- [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide)
|
||||
- [A Guide to SimpleDateFormat](https://www.baeldung.com/java-simple-date-format)
|
||||
- [SSL Handshake Failures](https://www.baeldung.com/java-ssl-handshake-failures)
|
||||
|
||||
@@ -157,7 +157,7 @@
|
||||
<dependency>
|
||||
<groupId>com.sun</groupId>
|
||||
<artifactId>tools</artifactId>
|
||||
<version>1.8.0</version>
|
||||
<version>${sun.tools.version}</version>
|
||||
<scope>system</scope>
|
||||
<systemPath>${java.home}/../lib/tools.jar</systemPath>
|
||||
</dependency>
|
||||
@@ -542,6 +542,8 @@
|
||||
<jmime-magic.version>0.1.5</jmime-magic.version>
|
||||
<!-- instrumentation -->
|
||||
<javaassist.version>3.21.0-GA</javaassist.version>
|
||||
|
||||
<sun.tools.version>1.8.0</sun.tools.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
package com.baeldung.accessmodifiers;
|
||||
|
||||
public class Public {
|
||||
public Public() {
|
||||
SuperPublic.publicMethod(); // Available everywhere.
|
||||
SuperPublic.protectedMethod(); // Available in the same package or subclass.
|
||||
SuperPublic.defaultMethod(); // Available in the same package.
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package com.baeldung.accessmodifiers;
|
||||
|
||||
public class SubClass extends SuperPublic {
|
||||
public SubClass() {
|
||||
SuperPublic.publicMethod(); // Available everywhere.
|
||||
SuperPublic.protectedMethod(); // Available in the same package or subclass.
|
||||
SuperPublic.defaultMethod(); // Available in the same package.
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
package com.baeldung.accessmodifiers;
|
||||
|
||||
//Only public or default access modifiers are permitted
|
||||
public class SuperPublic {
|
||||
// Always available from anywhere
|
||||
static public void publicMethod() {
|
||||
System.out.println(SuperPublic.class.getName() + " publicMethod()");
|
||||
}
|
||||
|
||||
// Available within the same package
|
||||
static void defaultMethod() {
|
||||
System.out.println(SuperPublic.class.getName() + " defaultMethod()");
|
||||
}
|
||||
|
||||
// Available within the same package and subclasses
|
||||
static protected void protectedMethod() {
|
||||
System.out.println(SuperPublic.class.getName() + " protectedMethod()");
|
||||
}
|
||||
|
||||
// Available within the same class only
|
||||
static private void privateMethod() {
|
||||
System.out.println(SuperPublic.class.getName() + " privateMethod()");
|
||||
}
|
||||
|
||||
// Method in the same class = has access to all members within the same class
|
||||
private void anotherPrivateMethod() {
|
||||
privateMethod();
|
||||
defaultMethod();
|
||||
protectedMethod();
|
||||
publicMethod(); // Available in the same class only.
|
||||
}
|
||||
}
|
||||
|
||||
// Only public or default access modifiers are permitted
|
||||
class SuperDefault {
|
||||
public void publicMethod() {
|
||||
System.out.println(this.getClass().getName() + " publicMethod()");
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package com.baeldung.accessmodifiers.another;
|
||||
|
||||
import com.baeldung.accessmodifiers.SuperPublic;
|
||||
|
||||
public class AnotherPublic {
|
||||
public AnotherPublic() {
|
||||
SuperPublic.publicMethod(); // Available everywhere.
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package com.baeldung.accessmodifiers.another;
|
||||
|
||||
import com.baeldung.accessmodifiers.SuperPublic;
|
||||
|
||||
public class AnotherSubClass extends SuperPublic {
|
||||
public AnotherSubClass() {
|
||||
SuperPublic.publicMethod(); // Available everywhere.
|
||||
SuperPublic.protectedMethod(); // Available in subclass. Let's note different package.
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package com.baeldung.accessmodifiers.another;
|
||||
|
||||
import com.baeldung.accessmodifiers.SuperPublic;
|
||||
|
||||
public class AnotherSuperPublic {
|
||||
public AnotherSuperPublic() {
|
||||
SuperPublic.publicMethod(); // Available everywhere. Let's note different package.
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
package com.baeldung.array;
|
||||
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
public class ArrayBenchmarkRunner {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
Options options = new OptionsBuilder()
|
||||
.include(SearchArrayUnitTest.class.getSimpleName()).threads(1)
|
||||
.forks(1).shouldFailOnError(true).shouldDoGC(true)
|
||||
.jvmArgs("-server").build();
|
||||
|
||||
new Runner(options).run();
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
package com.baeldung.array;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.apache.commons.lang.ArrayUtils;
|
||||
|
||||
public class ArrayInitializer {
|
||||
|
||||
static int[] initializeArrayInLoop() {
|
||||
int array[] = new int[5];
|
||||
for (int i = 0; i < array.length; i++) {
|
||||
array[i] = i + 2;
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
static int[][] initializeMultiDimensionalArrayInLoop() {
|
||||
int array[][] = new int[2][5];
|
||||
for (int i = 0; i < 2; i++) {
|
||||
for (int j = 0; j < 5; j++) {
|
||||
array[i][j] = j + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return array;
|
||||
}
|
||||
|
||||
static String[] initializeArrayAtTimeOfDeclarationMethod1() {
|
||||
String array[] = new String[] { "Toyota", "Mercedes", "BMW", "Volkswagen", "Skoda" };
|
||||
return array;
|
||||
}
|
||||
|
||||
static int[] initializeArrayAtTimeOfDeclarationMethod2() {
|
||||
int[] array = new int[] { 1, 2, 3, 4, 5 };
|
||||
return array;
|
||||
}
|
||||
|
||||
static int[] initializeArrayAtTimeOfDeclarationMethod3() {
|
||||
int array[] = { 1, 2, 3, 4, 5 };
|
||||
return array;
|
||||
}
|
||||
|
||||
static long[] initializeArrayUsingArraysFill() {
|
||||
long array[] = new long[5];
|
||||
Arrays.fill(array, 30);
|
||||
return array;
|
||||
}
|
||||
|
||||
static int[] initializeArrayRangeUsingArraysFill() {
|
||||
int array[] = new int[5];
|
||||
Arrays.fill(array, 0, 3, -50);
|
||||
return array;
|
||||
}
|
||||
|
||||
static int[] initializeArrayUsingArraysCopy() {
|
||||
int array[] = { 1, 2, 3, 4, 5 };
|
||||
int[] copy = Arrays.copyOf(array, 5);
|
||||
return copy;
|
||||
}
|
||||
|
||||
static int[] initializeLargerArrayUsingArraysCopy() {
|
||||
int array[] = { 1, 2, 3, 4, 5 };
|
||||
int[] copy = Arrays.copyOf(array, 6);
|
||||
return copy;
|
||||
}
|
||||
|
||||
static int[] initializeArrayUsingArraysSetAll() {
|
||||
int[] array = new int[20];
|
||||
|
||||
Arrays.setAll(array, p -> p > 9 ? 0 : p);
|
||||
return array;
|
||||
}
|
||||
|
||||
static char[] initializeArrayUsingArraysUtilClone() {
|
||||
char[] array = new char[] { 'a', 'b', 'c' };
|
||||
return ArrayUtils.clone(array);
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
package com.baeldung.array;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
public class ArrayInverter {
|
||||
|
||||
public void invertUsingFor(Object[] array) {
|
||||
for (int i = 0; i < array.length / 2; i++) {
|
||||
Object temp = array[i];
|
||||
array[i] = array[array.length - 1 - i];
|
||||
array[array.length - 1 - i] = temp;
|
||||
}
|
||||
}
|
||||
|
||||
public void invertUsingCollectionsReverse(Object[] array) {
|
||||
List<Object> list = Arrays.asList(array);
|
||||
Collections.reverse(list);
|
||||
}
|
||||
|
||||
public Object[] invertUsingStreams(final Object[] array) {
|
||||
return IntStream.rangeClosed(1, array.length)
|
||||
.mapToObj(i -> array[array.length - i])
|
||||
.toArray();
|
||||
}
|
||||
|
||||
public void invertUsingCommonsLang(Object[] array) {
|
||||
ArrayUtils.reverse(array);
|
||||
}
|
||||
|
||||
public Object[] invertUsingGuava(Object[] array) {
|
||||
List<Object> list = Arrays.asList(array);
|
||||
List<Object> reverted = Lists.reverse(list);
|
||||
return reverted.toArray();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,159 +0,0 @@
|
||||
package com.baeldung.array;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class ArrayReferenceGuide {
|
||||
|
||||
public static void main(String[] args) {
|
||||
declaration();
|
||||
|
||||
initialization();
|
||||
|
||||
access();
|
||||
|
||||
iterating();
|
||||
|
||||
varargs();
|
||||
|
||||
transformIntoList();
|
||||
|
||||
transformIntoStream();
|
||||
|
||||
sort();
|
||||
|
||||
search();
|
||||
|
||||
merge();
|
||||
}
|
||||
|
||||
private static void declaration() {
|
||||
int[] anArray;
|
||||
int anotherArray[];
|
||||
}
|
||||
|
||||
private static void initialization() {
|
||||
int[] anArray = new int[10];
|
||||
anArray[0] = 10;
|
||||
anArray[5] = 4;
|
||||
|
||||
int[] anotherArray = new int[] {1, 2, 3, 4, 5};
|
||||
}
|
||||
|
||||
private static void access() {
|
||||
int[] anArray = new int[10];
|
||||
anArray[0] = 10;
|
||||
anArray[5] = 4;
|
||||
|
||||
System.out.println(anArray[0]);
|
||||
}
|
||||
|
||||
private static void iterating() {
|
||||
int[] anArray = new int[] {1, 2, 3, 4, 5};
|
||||
for (int i = 0; i < anArray.length; i++) {
|
||||
System.out.println(anArray[i]);
|
||||
}
|
||||
|
||||
for (int element : anArray) {
|
||||
System.out.println(element);
|
||||
}
|
||||
}
|
||||
|
||||
private static void varargs() {
|
||||
String[] groceries = new String[] {"Milk", "Tomato", "Chips"};
|
||||
varargMethod(groceries);
|
||||
varargMethod("Milk", "Tomato", "Chips");
|
||||
}
|
||||
|
||||
private static void varargMethod(String... varargs) {
|
||||
for (String element : varargs) {
|
||||
System.out.println(element);
|
||||
}
|
||||
}
|
||||
|
||||
private static void transformIntoList() {
|
||||
Integer[] anArray = new Integer[] {1, 2, 3, 4, 5};
|
||||
|
||||
// Naïve implementation
|
||||
List<Integer> aList = new ArrayList<>(); // We create an empty list
|
||||
for (int element : anArray) {
|
||||
// We iterate over array's elements and add them to the list
|
||||
aList.add(element);
|
||||
}
|
||||
|
||||
// Pretty implementation
|
||||
aList = Arrays.asList(anArray);
|
||||
|
||||
// Drawbacks
|
||||
try {
|
||||
aList.remove(0);
|
||||
} catch (UnsupportedOperationException e) {
|
||||
System.out.println(e.getMessage());
|
||||
}
|
||||
|
||||
try {
|
||||
aList.add(6);
|
||||
} catch (UnsupportedOperationException e) {
|
||||
System.out.println(e.getMessage());
|
||||
}
|
||||
|
||||
int[] anotherArray = new int[] {1, 2, 3, 4, 5};
|
||||
// List<Integer> anotherList = Arrays.asList(anotherArray);
|
||||
}
|
||||
|
||||
private static void transformIntoStream() {
|
||||
int[] anArray = new int[] {1, 2, 3, 4, 5};
|
||||
IntStream aStream = Arrays.stream(anArray);
|
||||
|
||||
Integer[] anotherArray = new Integer[] {1, 2, 3, 4, 5};
|
||||
Stream<Integer> anotherStream = Arrays.stream(anotherArray, 2, 4);
|
||||
}
|
||||
|
||||
private static void sort() {
|
||||
int[] anArray = new int[] {5, 2, 1, 4, 8};
|
||||
Arrays.sort(anArray); // anArray is now {1, 2, 4, 5, 8}
|
||||
|
||||
Integer[] anotherArray = new Integer[] {5, 2, 1, 4, 8};
|
||||
Arrays.sort(anotherArray); // anArray is now {1, 2, 4, 5, 8}
|
||||
|
||||
String[] yetAnotherArray = new String[] {"A", "E", "Z", "B", "C"};
|
||||
Arrays.sort(yetAnotherArray, 1, 3, Comparator.comparing(String::toString).reversed()); // yetAnotherArray is now {"A", "Z", "E", "B", "C"}
|
||||
}
|
||||
|
||||
private static void search() {
|
||||
int[] anArray = new int[] {5, 2, 1, 4, 8};
|
||||
for (int i = 0; i < anArray.length; i++) {
|
||||
if (anArray[i] == 4) {
|
||||
System.out.println("Found at index " + i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Arrays.sort(anArray);
|
||||
int index = Arrays.binarySearch(anArray, 4);
|
||||
System.out.println("Found at index " + index);
|
||||
}
|
||||
|
||||
private static void merge() {
|
||||
int[] anArray = new int[] {5, 2, 1, 4, 8};
|
||||
int[] anotherArray = new int[] {10, 4, 9, 11, 2};
|
||||
|
||||
int[] resultArray = new int[anArray.length + anotherArray.length];
|
||||
for (int i = 0; i < resultArray.length; i++) {
|
||||
resultArray[i] = (i < anArray.length ? anArray[i] : anotherArray[i - anArray.length]);
|
||||
}
|
||||
for (int element : resultArray) {
|
||||
System.out.println(element);
|
||||
}
|
||||
|
||||
Arrays.setAll(resultArray, i -> (i < anArray.length ? anArray[i] : anotherArray[i - anArray.length]));
|
||||
for (int element : resultArray) {
|
||||
System.out.println(element);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package com.baeldung.array;
|
||||
|
||||
public class Find2ndLargestInArray {
|
||||
|
||||
public static int find2ndLargestElement(int[] array) {
|
||||
int maxElement = array[0];
|
||||
int secondLargestElement = -1;
|
||||
|
||||
for (int index = 0; index < array.length; index++) {
|
||||
if (maxElement <= array[index]) {
|
||||
secondLargestElement = maxElement;
|
||||
maxElement = array[index];
|
||||
} else if (secondLargestElement < array[index]) {
|
||||
secondLargestElement = array[index];
|
||||
}
|
||||
}
|
||||
return secondLargestElement;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package com.baeldung.array;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class FindElementInArray {
|
||||
|
||||
public static boolean findGivenElementInArrayWithoutUsingStream(int[] array, int element) {
|
||||
boolean actualResult = false;
|
||||
|
||||
for (int index = 0; index < array.length; index++) {
|
||||
if (element == array[index]) {
|
||||
actualResult = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return actualResult;
|
||||
}
|
||||
|
||||
public static boolean findGivenElementInArrayUsingStream(int[] array, int element) {
|
||||
return Arrays.stream(array).filter(x -> element == x).findFirst().isPresent();
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
package com.baeldung.array;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class JaggedArray {
|
||||
|
||||
int[][] shortHandFormInitialization() {
|
||||
int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } };
|
||||
return jaggedArr;
|
||||
}
|
||||
|
||||
int[][] declarationAndThenInitialization() {
|
||||
int[][] jaggedArr = new int[3][];
|
||||
jaggedArr[0] = new int[] { 1, 2 };
|
||||
jaggedArr[1] = new int[] { 3, 4, 5 };
|
||||
jaggedArr[2] = new int[] { 6, 7, 8, 9 };
|
||||
return jaggedArr;
|
||||
}
|
||||
|
||||
int[][] declarationAndThenInitializationUsingUserInputs() {
|
||||
int[][] jaggedArr = new int[3][];
|
||||
jaggedArr[0] = new int[2];
|
||||
jaggedArr[1] = new int[3];
|
||||
jaggedArr[2] = new int[4];
|
||||
initializeElements(jaggedArr);
|
||||
return jaggedArr;
|
||||
}
|
||||
|
||||
void initializeElements(int[][] jaggedArr) {
|
||||
Scanner sc = new Scanner(System.in);
|
||||
for (int outer = 0; outer < jaggedArr.length; outer++) {
|
||||
for (int inner = 0; inner < jaggedArr[outer].length; inner++) {
|
||||
jaggedArr[outer][inner] = sc.nextInt();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void printElements(int[][] jaggedArr) {
|
||||
for (int index = 0; index < jaggedArr.length; index++) {
|
||||
System.out.println(Arrays.toString(jaggedArr[index]));
|
||||
}
|
||||
}
|
||||
|
||||
int[] getElementAtGivenIndex(int[][] jaggedArr, int index) {
|
||||
return jaggedArr[index];
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
package com.baeldung.array;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@Warmup(iterations = 5)
|
||||
@OutputTimeUnit(TimeUnit.MICROSECONDS)
|
||||
public class SearchArrayUnitTest {
|
||||
|
||||
@State(Scope.Benchmark)
|
||||
public static class SearchData {
|
||||
static int count = 1000;
|
||||
static String[] strings = seedArray(1000);
|
||||
}
|
||||
|
||||
|
||||
@Benchmark
|
||||
public void searchArrayLoop() {
|
||||
for (int i = 0; i < SearchData.count; i++) {
|
||||
searchLoop(SearchData.strings, "T");
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void searchArrayAllocNewList() {
|
||||
for (int i = 0; i < SearchData.count; i++) {
|
||||
searchList(SearchData.strings, "T");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void searchArrayAllocNewSet() {
|
||||
for (int i = 0; i < SearchData.count; i++) {
|
||||
searchSet(SearchData.strings, "T");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Benchmark
|
||||
public void searchArrayReuseList() {
|
||||
List<String> asList = Arrays.asList(SearchData.strings);
|
||||
for (int i = 0; i < SearchData.count; i++) {
|
||||
asList.contains("T");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Benchmark
|
||||
public void searchArrayReuseSet() {
|
||||
Set<String> asSet = new HashSet<>(Arrays.asList(SearchData.strings));
|
||||
for (int i = 0; i < SearchData.count; i++) {
|
||||
asSet.contains("T");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Benchmark
|
||||
public void searchArrayBinarySearch() {
|
||||
Arrays.sort(SearchData.strings);
|
||||
for (int i = 0; i < SearchData.count; i++) {
|
||||
Arrays.binarySearch(SearchData.strings, "T");
|
||||
}
|
||||
}
|
||||
|
||||
private boolean searchList(String[] strings, String searchString) {
|
||||
return Arrays.asList(strings).contains(searchString);
|
||||
}
|
||||
|
||||
private boolean searchSet(String[] strings, String searchString) {
|
||||
Set<String> set = new HashSet<>(Arrays.asList(strings));
|
||||
return set.contains(searchString);
|
||||
}
|
||||
|
||||
private boolean searchLoop(String[] strings, String searchString) {
|
||||
for (String s : strings) {
|
||||
if (s.equals(searchString))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static String[] seedArray(int length) {
|
||||
String[] strings = new String[length];
|
||||
Random random = new Random();
|
||||
for (int i = 0; i < length; i++)
|
||||
{
|
||||
strings[i] = String.valueOf(random.nextInt());
|
||||
}
|
||||
return strings;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
package com.baeldung.array;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class SumAndAverageInArray {
|
||||
|
||||
public static int findSumWithoutUsingStream(int[] array) {
|
||||
int sum = 0;
|
||||
for (int value : array) {
|
||||
sum += value;
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
public static int findSumUsingStream(int[] array) {
|
||||
return Arrays.stream(array).sum();
|
||||
}
|
||||
|
||||
public static int findSumUsingStream(Integer[] array) {
|
||||
return Arrays.stream(array).mapToInt(Integer::intValue).sum();
|
||||
}
|
||||
|
||||
public static double findAverageWithoutUsingStream(int[] array) {
|
||||
int sum = findSumWithoutUsingStream(array);
|
||||
return (double) sum / array.length;
|
||||
}
|
||||
|
||||
public static double findAverageUsingStream(int[] array) {
|
||||
return Arrays.stream(array).average().orElse(Double.NaN);
|
||||
}
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
package com.baeldung.arraycopy.model;
|
||||
|
||||
public class Address implements Cloneable {
|
||||
private String country;
|
||||
private String state;
|
||||
private String city;
|
||||
private String street;
|
||||
private String zipcode;
|
||||
|
||||
public String getCountry() {
|
||||
return country;
|
||||
}
|
||||
|
||||
public void setCountry(String country) {
|
||||
this.country = country;
|
||||
}
|
||||
|
||||
public String getState() {
|
||||
return state;
|
||||
}
|
||||
|
||||
public void setState(String state) {
|
||||
this.state = state;
|
||||
}
|
||||
|
||||
public String getCity() {
|
||||
return city;
|
||||
}
|
||||
|
||||
public void setCity(String city) {
|
||||
this.city = city;
|
||||
}
|
||||
|
||||
public String getStreet() {
|
||||
return street;
|
||||
}
|
||||
|
||||
public void setStreet(String street) {
|
||||
this.street = street;
|
||||
}
|
||||
|
||||
public String getZipcode() {
|
||||
return zipcode;
|
||||
}
|
||||
|
||||
public void setZipcode(String zipcode) {
|
||||
this.zipcode = zipcode;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object clone() throws CloneNotSupportedException {
|
||||
super.clone();
|
||||
Address address = new Address();
|
||||
address.setCity(this.city);
|
||||
address.setCountry(this.country);
|
||||
address.setState(this.state);
|
||||
address.setStreet(this.street);
|
||||
address.setZipcode(this.zipcode);
|
||||
return address;
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package com.baeldung.arraycopy.model;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class Employee implements Serializable {
|
||||
private static final long serialVersionUID = -2454619097207585825L;
|
||||
private int id;
|
||||
private String name;
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package com.baeldung.assertion;
|
||||
|
||||
/**
|
||||
* Simple demonstration of using Java assert keyword.
|
||||
*/
|
||||
public class Assertion {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Assertion assertion = new Assertion();
|
||||
assertion.setup();
|
||||
}
|
||||
|
||||
public void setup() {
|
||||
Object conn = getConnection();
|
||||
assert conn != null : "Connection is null";
|
||||
|
||||
// continue with other setup ...
|
||||
}
|
||||
|
||||
// Simulate failure to get a connection; using Object
|
||||
// to avoid dependencies on JDBC or some other heavy
|
||||
// 3rd party library
|
||||
public Object getConnection() {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package com.baeldung.binding;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Created by madhumita.g on 25-07-2018.
|
||||
*/
|
||||
public class Animal {
|
||||
|
||||
final static Logger logger = LoggerFactory.getLogger(Animal.class);
|
||||
|
||||
public void makeNoise() {
|
||||
logger.info("generic animal noise");
|
||||
}
|
||||
|
||||
public void makeNoise(Integer repetitions) {
|
||||
while(repetitions != 0) {
|
||||
logger.info("generic animal noise countdown " + repetitions);
|
||||
repetitions -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
package com.baeldung.binding;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Created by madhumita.g on 25-07-2018.
|
||||
*/
|
||||
public class AnimalActivity {
|
||||
|
||||
final static Logger logger = LoggerFactory.getLogger(AnimalActivity.class);
|
||||
|
||||
|
||||
public static void sleep(Animal animal) {
|
||||
logger.info("Animal is sleeping");
|
||||
}
|
||||
|
||||
public static void sleep(Cat cat) {
|
||||
logger.info("Cat is sleeping");
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
Animal animal = new Animal();
|
||||
|
||||
//calling methods of animal object
|
||||
animal.makeNoise();
|
||||
|
||||
animal.makeNoise(3);
|
||||
|
||||
|
||||
//assigning a dog object to reference of type Animal
|
||||
Animal catAnimal = new Cat();
|
||||
|
||||
catAnimal.makeNoise();
|
||||
|
||||
// calling static function
|
||||
AnimalActivity.sleep(catAnimal);
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package com.baeldung.binding;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Created by madhumita.g on 25-07-2018.
|
||||
*/
|
||||
public class Cat extends Animal {
|
||||
|
||||
final static Logger logger = LoggerFactory.getLogger(Cat.class);
|
||||
|
||||
public void makeNoise() {
|
||||
|
||||
logger.info("meow");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
package com.baeldung.breakcontinue;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
|
||||
/**
|
||||
* @author Santosh
|
||||
*
|
||||
*/
|
||||
public class BreakContinue {
|
||||
|
||||
public static int unlabeledBreak() {
|
||||
String searchName = "Wilson";
|
||||
int counter = 0;
|
||||
List<String> names = Arrays.asList("John", "Peter", "Robert", "Wilson", "Anthony", "Donald", "Richard");
|
||||
|
||||
for (String name : names) {
|
||||
counter++;
|
||||
if (name.equalsIgnoreCase(searchName)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return counter;
|
||||
}
|
||||
|
||||
public static int unlabeledBreakNestedLoops() {
|
||||
String searchName = "Wilson";
|
||||
int counter = 0;
|
||||
Map<String, List<String>> nameMap = new HashMap<>();
|
||||
nameMap.put("Grade1", Arrays.asList("John", "Peter", "Robert", "Wilson"));
|
||||
nameMap.put("Grade2", Arrays.asList("Anthony", "Donald", "Richard", "Arnold"));
|
||||
nameMap.put("Grade3", Arrays.asList("Wilson", "Michael", "Stephen", "Ryan"));
|
||||
|
||||
Iterator<Entry<String, List<String>>> iterator = nameMap.entrySet()
|
||||
.iterator();
|
||||
Entry<String, List<String>> entry = null;
|
||||
List<String> names = null;
|
||||
while (iterator.hasNext()) {
|
||||
entry = iterator.next();
|
||||
names = entry.getValue();
|
||||
for (String name : names) {
|
||||
if (name.equalsIgnoreCase(searchName)) {
|
||||
counter++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return counter;
|
||||
}
|
||||
|
||||
public static int labeledBreak() {
|
||||
String searchName = "Wilson";
|
||||
int counter = 0;
|
||||
Map<String, List<String>> nameMap = new HashMap<>();
|
||||
nameMap.put("Grade1", Arrays.asList("John", "Peter", "Robert", "Wilson"));
|
||||
nameMap.put("Grade2", Arrays.asList("Anthony", "Donald", "Richard", "Arnold"));
|
||||
nameMap.put("Grade3", Arrays.asList("Wilson", "Michael", "Stephen", "Ryan"));
|
||||
|
||||
Iterator<Entry<String, List<String>>> iterator = nameMap.entrySet()
|
||||
.iterator();
|
||||
Entry<String, List<String>> entry = null;
|
||||
List<String> names = null;
|
||||
compare:
|
||||
while (iterator.hasNext()) {
|
||||
entry = iterator.next();
|
||||
names = entry.getValue();
|
||||
for (String name : names) {
|
||||
if (name.equalsIgnoreCase(searchName)) {
|
||||
counter++;
|
||||
break compare;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return counter;
|
||||
}
|
||||
|
||||
public static int unlabeledContinue() {
|
||||
String searchName = "Wilson";
|
||||
int counter = 0;
|
||||
Map<String, List<String>> nameMap = new HashMap<>();
|
||||
nameMap.put("Grade1", Arrays.asList("John", "Wilson", "Robert", "Wilson"));
|
||||
nameMap.put("Grade2", Arrays.asList("Anthony", "Donald", "Wilson", "Arnold"));
|
||||
nameMap.put("Grade3", Arrays.asList("Wilson", "Michael", "Wilson", "Ryan"));
|
||||
|
||||
Iterator<Entry<String, List<String>>> iterator = nameMap.entrySet()
|
||||
.iterator();
|
||||
Entry<String, List<String>> entry = null;
|
||||
List<String> names = null;
|
||||
while (iterator.hasNext()) {
|
||||
entry = iterator.next();
|
||||
names = entry.getValue();
|
||||
for (String name : names) {
|
||||
if (!name.equalsIgnoreCase(searchName)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
counter++;
|
||||
}
|
||||
}
|
||||
|
||||
return counter;
|
||||
}
|
||||
|
||||
public static int labeledContinue() {
|
||||
String searchName = "Wilson";
|
||||
int counter = 0;
|
||||
Map<String, List<String>> nameMap = new HashMap<>();
|
||||
nameMap.put("Grade1", Arrays.asList("John", "Wilson", "Robert", "Wilson"));
|
||||
nameMap.put("Grade2", Arrays.asList("Anthony", "Donald", "Wilson", "Arnold"));
|
||||
nameMap.put("Grade3", Arrays.asList("Wilson", "Michael", "Wilson", "Ryan"));
|
||||
|
||||
Iterator<Entry<String, List<String>>> iterator = nameMap.entrySet()
|
||||
.iterator();
|
||||
Entry<String, List<String>> entry = null;
|
||||
List<String> names = null;
|
||||
compare:
|
||||
while (iterator.hasNext()) {
|
||||
entry = iterator.next();
|
||||
names = entry.getValue();
|
||||
for (String name : names) {
|
||||
if (name.equalsIgnoreCase(searchName)) {
|
||||
counter++;
|
||||
continue compare;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return counter;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package com.baeldung.casting;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class Animal {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(Animal.class);
|
||||
|
||||
public void eat() {
|
||||
LOGGER.info("animal is eating");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package com.baeldung.casting;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class AnimalFeeder {
|
||||
|
||||
public void feed(List<Animal> animals) {
|
||||
animals.forEach(animal -> {
|
||||
animal.eat();
|
||||
if (animal instanceof Cat) {
|
||||
((Cat) animal).meow();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void uncheckedFeed(List<Animal> animals) {
|
||||
animals.forEach(animal -> {
|
||||
animal.eat();
|
||||
((Cat) animal).meow();
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package com.baeldung.casting;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class AnimalFeederGeneric<T> {
|
||||
private Class<T> type;
|
||||
|
||||
public AnimalFeederGeneric(Class<T> type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public List<T> feed(List<Animal> animals) {
|
||||
List<T> list = new ArrayList<T>();
|
||||
animals.forEach(animal -> {
|
||||
if (type.isInstance(animal)) {
|
||||
T objAsType = type.cast(animal);
|
||||
list.add(objAsType);
|
||||
}
|
||||
});
|
||||
return list;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
package com.baeldung.casting;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class Cat extends Animal implements Mew {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(Cat.class);
|
||||
|
||||
public void eat() {
|
||||
LOGGER.info("cat is eating");
|
||||
}
|
||||
|
||||
public void meow() {
|
||||
LOGGER.info("meow");
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package com.baeldung.casting;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class Dog extends Animal {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(Dog.class);
|
||||
|
||||
public void eat() {
|
||||
LOGGER.info("dog is eating");
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package com.baeldung.casting;
|
||||
|
||||
public interface Mew {
|
||||
public void meow();
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
package com.baeldung.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;
|
||||
|
||||
public class LogWithChain {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
getLeave();
|
||||
}
|
||||
|
||||
private static void getLeave() throws NoLeaveGrantedException {
|
||||
try {
|
||||
howIsTeamLead();
|
||||
} catch (TeamLeadUpsetException e) {
|
||||
throw new NoLeaveGrantedException("Leave not sanctioned.", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void howIsTeamLead() throws TeamLeadUpsetException {
|
||||
try {
|
||||
howIsManager();
|
||||
} catch (ManagerUpsetException e) {
|
||||
throw new TeamLeadUpsetException("Team lead is not in good mood", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void howIsManager() throws ManagerUpsetException {
|
||||
try {
|
||||
howIsGirlFriendOfManager();
|
||||
} catch (GirlFriendOfManagerUpsetException e) {
|
||||
throw new ManagerUpsetException("Manager is in bad mood", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void howIsGirlFriendOfManager() throws GirlFriendOfManagerUpsetException {
|
||||
throw new GirlFriendOfManagerUpsetException("Girl friend of manager is in bad mood");
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
package com.baeldung.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;
|
||||
|
||||
public class LogWithoutChain {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
getLeave();
|
||||
}
|
||||
|
||||
private static void getLeave() throws NoLeaveGrantedException {
|
||||
try {
|
||||
howIsTeamLead();
|
||||
} catch (TeamLeadUpsetException e) {
|
||||
e.printStackTrace();
|
||||
throw new NoLeaveGrantedException("Leave not sanctioned.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void howIsTeamLead() throws TeamLeadUpsetException {
|
||||
try {
|
||||
howIsManager();
|
||||
} catch (ManagerUpsetException e) {
|
||||
e.printStackTrace();
|
||||
throw new TeamLeadUpsetException("Team lead is not in good mood");
|
||||
}
|
||||
}
|
||||
|
||||
private static void howIsManager() throws ManagerUpsetException {
|
||||
try {
|
||||
howIsGirlFriendOfManager();
|
||||
} catch (GirlFriendOfManagerUpsetException e) {
|
||||
e.printStackTrace();
|
||||
throw new ManagerUpsetException("Manager is in bad mood");
|
||||
}
|
||||
}
|
||||
|
||||
private static void howIsGirlFriendOfManager() throws GirlFriendOfManagerUpsetException {
|
||||
throw new GirlFriendOfManagerUpsetException("Girl friend of manager is in bad mood");
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package com.baeldung.chainedexception.exceptions;
|
||||
|
||||
public class GirlFriendOfManagerUpsetException extends Exception {
|
||||
|
||||
public GirlFriendOfManagerUpsetException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public GirlFriendOfManagerUpsetException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package com.baeldung.chainedexception.exceptions;
|
||||
|
||||
public class ManagerUpsetException extends Exception {
|
||||
|
||||
public ManagerUpsetException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public ManagerUpsetException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package com.baeldung.chainedexception.exceptions;
|
||||
|
||||
public class NoLeaveGrantedException extends Exception {
|
||||
|
||||
public NoLeaveGrantedException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public NoLeaveGrantedException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package com.baeldung.chainedexception.exceptions;
|
||||
|
||||
public class TeamLeadUpsetException extends Exception {
|
||||
|
||||
public TeamLeadUpsetException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public TeamLeadUpsetException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
package com.baeldung.comparable;
|
||||
|
||||
public class Player implements Comparable<Player> {
|
||||
|
||||
private int ranking;
|
||||
|
||||
private String name;
|
||||
|
||||
private int age;
|
||||
|
||||
public Player(int ranking, String name, int age) {
|
||||
this.ranking = ranking;
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public int getRanking() {
|
||||
return ranking;
|
||||
}
|
||||
|
||||
public void setRanking(int ranking) {
|
||||
this.ranking = ranking;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(Player otherPlayer) {
|
||||
return (this.getRanking() - otherPlayer.getRanking());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package com.baeldung.comparable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class PlayerSorter {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
List<Player> footballTeam = new ArrayList<Player>();
|
||||
Player player1 = new Player(59, "John", 20);
|
||||
Player player2 = new Player(67, "Roger", 22);
|
||||
Player player3 = new Player(45, "Steven", 24);
|
||||
footballTeam.add(player1);
|
||||
footballTeam.add(player2);
|
||||
footballTeam.add(player3);
|
||||
|
||||
System.out.println("Before Sorting : " + footballTeam);
|
||||
Collections.sort(footballTeam);
|
||||
System.out.println("After Sorting : " + footballTeam);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
package com.baeldung.comparator;
|
||||
|
||||
public class Player {
|
||||
|
||||
private int ranking;
|
||||
|
||||
private String name;
|
||||
|
||||
private int age;
|
||||
|
||||
public Player(int ranking, String name, int age) {
|
||||
this.ranking = ranking;
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public int getRanking() {
|
||||
return ranking;
|
||||
}
|
||||
|
||||
public void setRanking(int ranking) {
|
||||
this.ranking = ranking;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package com.baeldung.comparator;
|
||||
|
||||
import java.util.Comparator;
|
||||
|
||||
public class PlayerAgeComparator implements Comparator<Player> {
|
||||
|
||||
@Override
|
||||
public int compare(Player firstPlayer, Player secondPlayer) {
|
||||
return (firstPlayer.getAge() - secondPlayer.getAge());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package com.baeldung.comparator;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class PlayerAgeSorter {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
List<Player> footballTeam = new ArrayList<Player>();
|
||||
Player player1 = new Player(59, "John", 22);
|
||||
Player player2 = new Player(67, "Roger", 20);
|
||||
Player player3 = new Player(45, "Steven", 24);
|
||||
footballTeam.add(player1);
|
||||
footballTeam.add(player2);
|
||||
footballTeam.add(player3);
|
||||
|
||||
System.out.println("Before Sorting : " + footballTeam);
|
||||
//Instance of PlayerAgeComparator
|
||||
PlayerAgeComparator playerComparator = new PlayerAgeComparator();
|
||||
Collections.sort(footballTeam, playerComparator);
|
||||
System.out.println("After Sorting by age : " + footballTeam);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package com.baeldung.comparator;
|
||||
|
||||
import java.util.Comparator;
|
||||
|
||||
public class PlayerRankingComparator implements Comparator<Player> {
|
||||
|
||||
@Override
|
||||
public int compare(Player firstPlayer, Player secondPlayer) {
|
||||
return (firstPlayer.getRanking() - secondPlayer.getRanking());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package com.baeldung.comparator;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class PlayerRankingSorter {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
List<Player> footballTeam = new ArrayList<Player>();
|
||||
Player player1 = new Player(59, "John", 22);
|
||||
Player player2 = new Player(67, "Roger", 20);
|
||||
Player player3 = new Player(45, "Steven", 40);
|
||||
footballTeam.add(player1);
|
||||
footballTeam.add(player2);
|
||||
footballTeam.add(player3);
|
||||
|
||||
System.out.println("Before Sorting : " + footballTeam);
|
||||
//Instance of PlayerRankingComparator
|
||||
PlayerRankingComparator playerComparator = new PlayerRankingComparator();
|
||||
Collections.sort(footballTeam, playerComparator);
|
||||
System.out.println("After Sorting by ranking : " + footballTeam);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
package com.baeldung.customexception;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class FileManager {
|
||||
|
||||
public static String getFirstLine(String fileName) throws IncorrectFileNameException {
|
||||
try (Scanner file = new Scanner(new File(fileName))) {
|
||||
if (file.hasNextLine()) {
|
||||
return file.nextLine();
|
||||
} else {
|
||||
throw new IllegalArgumentException("Non readable file");
|
||||
}
|
||||
} catch (FileNotFoundException err) {
|
||||
if (!isCorrectFileName(fileName)) {
|
||||
throw new IncorrectFileNameException("Incorrect filename : " + fileName, err);
|
||||
}
|
||||
// Logging etc
|
||||
} catch (IllegalArgumentException err) {
|
||||
if (!containsExtension(fileName)) {
|
||||
throw new IncorrectFileExtensionException("Filename does not contain extension : " + fileName, err);
|
||||
}
|
||||
// Other error cases and logging
|
||||
}
|
||||
return "Default First Line";
|
||||
}
|
||||
|
||||
private static boolean containsExtension(String fileName) {
|
||||
if (fileName.contains(".txt") || fileName.contains(".doc"))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean isCorrectFileName(String fileName) {
|
||||
if (fileName.equals("wrongFileName.txt"))
|
||||
return false;
|
||||
else
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package com.baeldung.customexception;
|
||||
|
||||
public class IncorrectFileExtensionException extends RuntimeException{
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public IncorrectFileExtensionException(String errorMessage, Throwable err) {
|
||||
super(errorMessage, err);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package com.baeldung.customexception;
|
||||
|
||||
public class IncorrectFileNameException extends Exception {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public IncorrectFileNameException(String errorMessage, Throwable err) {
|
||||
super(errorMessage, err);
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
package com.baeldung.deepcopy;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class Address implements Serializable, Cloneable {
|
||||
|
||||
@Override
|
||||
public Object clone() {
|
||||
try {
|
||||
return (Address) super.clone();
|
||||
} catch (CloneNotSupportedException e) {
|
||||
return new Address(this.street, this.getCity(), this.getCountry());
|
||||
}
|
||||
}
|
||||
|
||||
private static final long serialVersionUID = 1740913841244949416L;
|
||||
private String street;
|
||||
private String city;
|
||||
|
||||
private String country;
|
||||
|
||||
public Address(Address that) {
|
||||
this(that.getStreet(), that.getCity(), that.getCountry());
|
||||
}
|
||||
|
||||
public Address(String street, String city, String country) {
|
||||
this.street = street;
|
||||
this.city = city;
|
||||
this.country = country;
|
||||
}
|
||||
|
||||
public Address() {
|
||||
}
|
||||
|
||||
public String getStreet() {
|
||||
return street;
|
||||
}
|
||||
|
||||
public String getCity() {
|
||||
return city;
|
||||
}
|
||||
|
||||
public String getCountry() {
|
||||
return country;
|
||||
}
|
||||
|
||||
public void setStreet(String street) {
|
||||
this.street = street;
|
||||
}
|
||||
|
||||
public void setCity(String city) {
|
||||
this.city = city;
|
||||
}
|
||||
|
||||
public void setCountry(String country) {
|
||||
this.country = country;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
package com.baeldung.deepcopy;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class User implements Serializable, Cloneable {
|
||||
|
||||
private static final long serialVersionUID = -3427002229954777557L;
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
private Address address;
|
||||
|
||||
public User(String firstName, String lastName, Address address) {
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
public User(User that) {
|
||||
this(that.getFirstName(), that.getLastName(), new Address(that.getAddress()));
|
||||
}
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object clone() {
|
||||
User user;
|
||||
try {
|
||||
user = (User) super.clone();
|
||||
} catch (CloneNotSupportedException e) {
|
||||
user = new User(this.getFirstName(), this.getLastName(), this.getAddress());
|
||||
}
|
||||
user.address = (Address) this.address.clone();
|
||||
return user;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public Address getAddress() {
|
||||
return address;
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
package com.baeldung.doubles;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
public class SplitFloatingPointNumbers {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
double doubleNumber = 24.04;
|
||||
splitUsingFloatingTypes(doubleNumber);
|
||||
splitUsingString(doubleNumber);
|
||||
splitUsingBigDecimal(doubleNumber);
|
||||
}
|
||||
|
||||
private static void splitUsingFloatingTypes(double doubleNumber) {
|
||||
System.out.println("Using Floating Point Arithmetics:");
|
||||
int intPart = (int) doubleNumber;
|
||||
System.out.println("Double Number: "+doubleNumber);
|
||||
System.out.println("Integer Part: "+ intPart);
|
||||
System.out.println("Decimal Part: "+ (doubleNumber - intPart));
|
||||
}
|
||||
|
||||
private static void splitUsingString(double doubleNumber) {
|
||||
System.out.println("Using String Operations:");
|
||||
String doubleAsString = String.valueOf(doubleNumber);
|
||||
int indexOfDecimal = doubleAsString.indexOf(".");
|
||||
System.out.println("Double Number: "+doubleNumber);
|
||||
System.out.println("Integer Part: "+ doubleAsString.substring(0, indexOfDecimal));
|
||||
System.out.println("Decimal Part: "+ doubleAsString.substring(indexOfDecimal));
|
||||
}
|
||||
|
||||
private static void splitUsingBigDecimal(double doubleNumber) {
|
||||
System.out.println("Using BigDecimal Operations:");
|
||||
BigDecimal bigDecimal = new BigDecimal(String.valueOf(doubleNumber));
|
||||
int intValue = bigDecimal.intValue();
|
||||
System.out.println("Double Number: "+bigDecimal.toPlainString());
|
||||
System.out.println("Integer Part: "+intValue);
|
||||
System.out.println("Decimal Part: "+bigDecimal.subtract(new BigDecimal(intValue)).toPlainString());
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
package com.baeldung.dynamicproxy;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
public class DynamicInvocationHandler implements InvocationHandler {
|
||||
|
||||
private static Logger LOGGER = LoggerFactory.getLogger(DynamicInvocationHandler.class);
|
||||
|
||||
@Override
|
||||
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
|
||||
LOGGER.info("Invoked method: {}", method.getName());
|
||||
|
||||
return 42;
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
package com.baeldung.dynamicproxy;
|
||||
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class TimingDynamicInvocationHandler implements InvocationHandler {
|
||||
|
||||
private static Logger LOGGER = LoggerFactory.getLogger(TimingDynamicInvocationHandler.class);
|
||||
private final Map<String, Method> methods = new HashMap<>();
|
||||
|
||||
private Object target;
|
||||
|
||||
TimingDynamicInvocationHandler(Object target) {
|
||||
this.target = target;
|
||||
|
||||
for(Method method: target.getClass().getDeclaredMethods()) {
|
||||
this.methods.put(method.getName(), method);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
|
||||
long start = System.nanoTime();
|
||||
Object result = methods.get(method.getName()).invoke(target, args);
|
||||
long elapsed = System.nanoTime() - start;
|
||||
|
||||
LOGGER.info("Executing {} finished in {} ns", method.getName(), elapsed);
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
package com.baeldung.enums;
|
||||
|
||||
import java.util.EnumMap;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class Pizza {
|
||||
|
||||
private static EnumSet<PizzaStatusEnum> deliveredPizzaStatuses = EnumSet.of(PizzaStatusEnum.DELIVERED);
|
||||
|
||||
private PizzaStatusEnum status;
|
||||
|
||||
public enum PizzaStatusEnum {
|
||||
ORDERED(5) {
|
||||
@Override
|
||||
public boolean isOrdered() {
|
||||
return true;
|
||||
}
|
||||
},
|
||||
READY(2) {
|
||||
@Override
|
||||
public boolean isReady() {
|
||||
return true;
|
||||
}
|
||||
},
|
||||
DELIVERED(0) {
|
||||
@Override
|
||||
public boolean isDelivered() {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
private int timeToDelivery;
|
||||
|
||||
public boolean isOrdered() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isReady() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isDelivered() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public int getTimeToDelivery() {
|
||||
return timeToDelivery;
|
||||
}
|
||||
|
||||
PizzaStatusEnum(int timeToDelivery) {
|
||||
this.timeToDelivery = timeToDelivery;
|
||||
}
|
||||
}
|
||||
|
||||
public PizzaStatusEnum getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(PizzaStatusEnum status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public boolean isDeliverable() {
|
||||
return this.status.isReady();
|
||||
}
|
||||
|
||||
public void printTimeToDeliver() {
|
||||
System.out.println("Time to delivery is " + this.getStatus().getTimeToDelivery() + " days");
|
||||
}
|
||||
|
||||
public static List<Pizza> getAllUndeliveredPizzas(List<Pizza> input) {
|
||||
return input.stream().filter((s) -> !deliveredPizzaStatuses.contains(s.getStatus())).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public static EnumMap<PizzaStatusEnum, List<Pizza>> groupPizzaByStatus(List<Pizza> pzList) {
|
||||
return pzList.stream().collect(Collectors.groupingBy(Pizza::getStatus, () -> new EnumMap<>(PizzaStatusEnum.class), Collectors.toList()));
|
||||
}
|
||||
|
||||
public void deliver() {
|
||||
if (isDeliverable()) {
|
||||
PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy().deliver(this);
|
||||
this.setStatus(PizzaStatusEnum.DELIVERED);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package com.baeldung.enums;
|
||||
|
||||
public enum PizzaDeliveryStrategy {
|
||||
EXPRESS {
|
||||
@Override
|
||||
public void deliver(Pizza pz) {
|
||||
System.out.println("Pizza will be delivered in express mode");
|
||||
}
|
||||
},
|
||||
NORMAL {
|
||||
@Override
|
||||
public void deliver(Pizza pz) {
|
||||
System.out.println("Pizza will be delivered in normal mode");
|
||||
}
|
||||
};
|
||||
|
||||
public abstract void deliver(Pizza pz);
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
package com.baeldung.enums;
|
||||
|
||||
public enum PizzaDeliverySystemConfiguration {
|
||||
INSTANCE;
|
||||
|
||||
PizzaDeliverySystemConfiguration() {
|
||||
// Do the configuration initialization which
|
||||
// involves overriding defaults like delivery strategy
|
||||
}
|
||||
|
||||
private PizzaDeliveryStrategy deliveryStrategy = PizzaDeliveryStrategy.NORMAL;
|
||||
|
||||
public static PizzaDeliverySystemConfiguration getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
public PizzaDeliveryStrategy getDeliveryStrategy() {
|
||||
return deliveryStrategy;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
### Relevant Articles:
|
||||
- [A Guide to Java Enums](http://www.baeldung.com/a-guide-to-java-enums)
|
||||
@@ -1,63 +0,0 @@
|
||||
package com.baeldung.equalshashcode.entities;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
public class ComplexClass {
|
||||
|
||||
private List<?> genericList;
|
||||
private Set<Integer> integerSet;
|
||||
|
||||
public ComplexClass(List<?> genericArrayList, Set<Integer> integerHashSet) {
|
||||
super();
|
||||
this.genericList = genericArrayList;
|
||||
this.integerSet = integerHashSet;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((genericList == null) ? 0 : genericList.hashCode());
|
||||
result = prime * result + ((integerSet == null) ? 0 : integerSet.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (!(obj instanceof ComplexClass))
|
||||
return false;
|
||||
ComplexClass other = (ComplexClass) obj;
|
||||
if (genericList == null) {
|
||||
if (other.genericList != null)
|
||||
return false;
|
||||
} else if (!genericList.equals(other.genericList))
|
||||
return false;
|
||||
if (integerSet == null) {
|
||||
if (other.integerSet != null)
|
||||
return false;
|
||||
} else if (!integerSet.equals(other.integerSet))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
protected List<?> getGenericList() {
|
||||
return genericList;
|
||||
}
|
||||
|
||||
protected void setGenericArrayList(List<?> genericList) {
|
||||
this.genericList = genericList;
|
||||
}
|
||||
|
||||
protected Set<Integer> getIntegerSet() {
|
||||
return integerSet;
|
||||
}
|
||||
|
||||
protected void setIntegerSet(Set<Integer> integerSet) {
|
||||
this.integerSet = integerSet;
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
package com.baeldung.equalshashcode.entities;
|
||||
|
||||
public class PrimitiveClass {
|
||||
|
||||
private boolean primitiveBoolean;
|
||||
private int primitiveInt;
|
||||
|
||||
public PrimitiveClass(boolean primitiveBoolean, int primitiveInt) {
|
||||
super();
|
||||
this.primitiveBoolean = primitiveBoolean;
|
||||
this.primitiveInt = primitiveInt;
|
||||
}
|
||||
|
||||
protected boolean isPrimitiveBoolean() {
|
||||
return primitiveBoolean;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + (primitiveBoolean ? 1231 : 1237);
|
||||
result = prime * result + primitiveInt;
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
PrimitiveClass other = (PrimitiveClass) obj;
|
||||
if (primitiveBoolean != other.primitiveBoolean)
|
||||
return false;
|
||||
if (primitiveInt != other.primitiveInt)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
protected void setPrimitiveBoolean(boolean primitiveBoolean) {
|
||||
this.primitiveBoolean = primitiveBoolean;
|
||||
}
|
||||
|
||||
protected int getPrimitiveInt() {
|
||||
return primitiveInt;
|
||||
}
|
||||
|
||||
protected void setPrimitiveInt(int primitiveInt) {
|
||||
this.primitiveInt = primitiveInt;
|
||||
}
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
package com.baeldung.equalshashcode.entities;
|
||||
|
||||
public class Rectangle extends Shape {
|
||||
private double width;
|
||||
private double length;
|
||||
|
||||
public Rectangle(double width, double length) {
|
||||
this.width = width;
|
||||
this.length = length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double area() {
|
||||
return width * length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double perimeter() {
|
||||
return 2 * (width + length);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
long temp;
|
||||
temp = Double.doubleToLongBits(length);
|
||||
result = prime * result + (int) (temp ^ (temp >>> 32));
|
||||
temp = Double.doubleToLongBits(width);
|
||||
result = prime * result + (int) (temp ^ (temp >>> 32));
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
Rectangle other = (Rectangle) obj;
|
||||
if (Double.doubleToLongBits(length) != Double.doubleToLongBits(other.length))
|
||||
return false;
|
||||
if (Double.doubleToLongBits(width) != Double.doubleToLongBits(other.width))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
protected double getWidth() {
|
||||
return width;
|
||||
}
|
||||
|
||||
protected double getLength() {
|
||||
return length;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
package com.baeldung.equalshashcode.entities;
|
||||
|
||||
public abstract class Shape {
|
||||
public abstract double area();
|
||||
|
||||
public abstract double perimeter();
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
package com.baeldung.equalshashcode.entities;
|
||||
|
||||
import java.awt.*;
|
||||
|
||||
public class Square extends Rectangle {
|
||||
|
||||
private Color color;
|
||||
|
||||
public Square(double width, Color color) {
|
||||
super(width, width);
|
||||
this.color = color;
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see java.lang.Object#hashCode()
|
||||
*/
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = super.hashCode();
|
||||
result = prime * result + ((color == null) ? 0 : color.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see java.lang.Object#equals(java.lang.Object)
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (!super.equals(obj)) {
|
||||
return false;
|
||||
}
|
||||
if (!(obj instanceof Square)) {
|
||||
return false;
|
||||
}
|
||||
Square other = (Square) obj;
|
||||
if (color == null) {
|
||||
if (other.color != null) {
|
||||
return false;
|
||||
}
|
||||
} else if (!color.equals(other.color)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
protected Color getColor() {
|
||||
return color;
|
||||
}
|
||||
|
||||
protected void setColor(Color color) {
|
||||
this.color = color;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,212 +0,0 @@
|
||||
package com.baeldung.exceptionhandling;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.List;
|
||||
import java.util.Scanner;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class Exceptions {
|
||||
|
||||
private final static Logger logger = Logger.getLogger("ExceptionLogging");
|
||||
|
||||
public static List<Player> getPlayers() throws IOException {
|
||||
Path path = Paths.get("players.dat");
|
||||
List<String> players = Files.readAllLines(path);
|
||||
|
||||
return players.stream()
|
||||
.map(Player::new)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public List<Player> loadAllPlayers(String playersFile) throws IOException{
|
||||
try {
|
||||
throw new IOException();
|
||||
} catch(IOException ex) {
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreThrows(String playerFile) throws FileNotFoundException {
|
||||
Scanner contents = new Scanner(new File(playerFile));
|
||||
return Integer.parseInt(contents.nextLine());
|
||||
}
|
||||
|
||||
public int getPlayerScoreTryCatch(String playerFile) {
|
||||
try {
|
||||
Scanner contents = new Scanner(new File(playerFile));
|
||||
return Integer.parseInt(contents.nextLine());
|
||||
} catch (FileNotFoundException noFile) {
|
||||
throw new IllegalArgumentException("File not found");
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreTryCatchRecovery(String playerFile) {
|
||||
try {
|
||||
Scanner contents = new Scanner(new File(playerFile));
|
||||
return Integer.parseInt(contents.nextLine());
|
||||
} catch ( FileNotFoundException noFile ) {
|
||||
logger.warning("File not found, resetting score.");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreFinally(String playerFile) throws FileNotFoundException {
|
||||
Scanner contents = null;
|
||||
try {
|
||||
contents = new Scanner(new File(playerFile));
|
||||
return Integer.parseInt(contents.nextLine());
|
||||
} finally {
|
||||
if (contents != null) {
|
||||
contents.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreTryWithResources(String playerFile) {
|
||||
try (Scanner contents = new Scanner(new File(playerFile))) {
|
||||
return Integer.parseInt(contents.nextLine());
|
||||
} catch (FileNotFoundException e ) {
|
||||
logger.warning("File not found, resetting score.");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreMultipleCatchBlocks(String playerFile) {
|
||||
try (Scanner contents = new Scanner(new File(playerFile))) {
|
||||
return Integer.parseInt(contents.nextLine());
|
||||
} catch (IOException e) {
|
||||
logger.warning("Player file wouldn't load!");
|
||||
return 0;
|
||||
} catch (NumberFormatException e) {
|
||||
logger.warning("Player file was corrupted!");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreMultipleCatchBlocksAlternative(String playerFile) {
|
||||
try (Scanner contents = new Scanner(new File(playerFile)) ) {
|
||||
return Integer.parseInt(contents.nextLine());
|
||||
} catch (FileNotFoundException e) {
|
||||
logger.warning("Player file not found!");
|
||||
return 0;
|
||||
} catch (IOException e) {
|
||||
logger.warning("Player file wouldn't load!");
|
||||
return 0;
|
||||
} catch (NumberFormatException e) {
|
||||
logger.warning("Player file was corrupted!");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreUnionCatchBlocks(String playerFile) {
|
||||
try (Scanner contents = new Scanner(new File(playerFile))) {
|
||||
return Integer.parseInt(contents.nextLine());
|
||||
} catch (IOException | NumberFormatException e) {
|
||||
logger.warning("Failed to load score!");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public List<Player> loadAllPlayersThrowingChecked(String playersFile) throws TimeoutException {
|
||||
boolean tooLong = true;
|
||||
|
||||
while (!tooLong) {
|
||||
// ... potentially long operation
|
||||
}
|
||||
throw new TimeoutException("This operation took too long");
|
||||
}
|
||||
|
||||
public List<Player> loadAllPlayersThrowingUnchecked(String playersFile) throws TimeoutException {
|
||||
if(!isFilenameValid(playersFile)) {
|
||||
throw new IllegalArgumentException("Filename isn't valid!");
|
||||
}
|
||||
return null;
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
public List<Player> loadAllPlayersWrapping(String playersFile) throws IOException {
|
||||
try {
|
||||
throw new IOException();
|
||||
} catch (IOException io) {
|
||||
throw io;
|
||||
}
|
||||
}
|
||||
|
||||
public List<Player> loadAllPlayersRethrowing(String playersFile) throws PlayerLoadException {
|
||||
try {
|
||||
throw new IOException();
|
||||
} catch (IOException io) {
|
||||
throw new PlayerLoadException(io);
|
||||
}
|
||||
}
|
||||
|
||||
public List<Player> loadAllPlayersThrowable(String playersFile) {
|
||||
try {
|
||||
throw new NullPointerException();
|
||||
} catch ( Throwable t ) {
|
||||
throw t;
|
||||
}
|
||||
}
|
||||
|
||||
class FewerExceptions extends Exceptions {
|
||||
@Override
|
||||
public List<Player> loadAllPlayers(String playersFile) { //can't add "throws MyCheckedException
|
||||
return null;
|
||||
// overridden
|
||||
}
|
||||
}
|
||||
|
||||
public void throwAsGotoAntiPattern() throws MyException {
|
||||
try {
|
||||
// bunch of code
|
||||
throw new MyException();
|
||||
// second bunch of code
|
||||
} catch ( MyException e ) {
|
||||
// third bunch of code
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreSwallowingExceptionAntiPattern(String playerFile) {
|
||||
try {
|
||||
// ...
|
||||
} catch (Exception e) {} // <== catch and swallow
|
||||
return 0;
|
||||
}
|
||||
|
||||
public int getPlayerScoreSwallowingExceptionAntiPatternAlternative(String playerFile) {
|
||||
try {
|
||||
// ...
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
public int getPlayerScoreSwallowingExceptionAntiPatternAlternative2(String playerFile) throws PlayerScoreException {
|
||||
try {
|
||||
throw new IOException();
|
||||
} catch (IOException e) {
|
||||
throw new PlayerScoreException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreReturnInFinallyAntiPattern(String playerFile) {
|
||||
int score = 0;
|
||||
try {
|
||||
throw new IOException();
|
||||
} finally {
|
||||
return score; // <== the IOException is dropped
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isFilenameValid(String name) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package com.baeldung.exceptionhandling;
|
||||
|
||||
public class MyException extends Throwable {
|
||||
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package com.baeldung.exceptionhandling;
|
||||
|
||||
public class Player {
|
||||
|
||||
public int id;
|
||||
public String name;
|
||||
|
||||
public Player(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
package com.baeldung.exceptionhandling;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class PlayerLoadException extends Exception {
|
||||
|
||||
public PlayerLoadException(IOException io) {
|
||||
super(io);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
package com.baeldung.exceptionhandling;
|
||||
|
||||
public class PlayerScoreException extends Exception {
|
||||
|
||||
public PlayerScoreException(Exception e) {
|
||||
super(e);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
package com.baeldung.exceptionhandling;
|
||||
|
||||
public class TimeoutException extends Exception {
|
||||
|
||||
public TimeoutException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
package com.baeldung.finalize;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
|
||||
public class CloseableResource implements AutoCloseable {
|
||||
private BufferedReader reader;
|
||||
|
||||
public CloseableResource() {
|
||||
InputStream input = this.getClass().getClassLoader().getResourceAsStream("file.txt");
|
||||
reader = new BufferedReader(new InputStreamReader(input));
|
||||
}
|
||||
|
||||
public String readFirstLine() throws IOException {
|
||||
String firstLine = reader.readLine();
|
||||
return firstLine;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
try {
|
||||
reader.close();
|
||||
System.out.println("Closed BufferedReader in the close method");
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
package com.baeldung.finalize;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
|
||||
public class Finalizable {
|
||||
private BufferedReader reader;
|
||||
|
||||
public Finalizable() {
|
||||
InputStream input = this.getClass().getClassLoader().getResourceAsStream("file.txt");
|
||||
reader = new BufferedReader(new InputStreamReader(input));
|
||||
}
|
||||
|
||||
public String readFirstLine() throws IOException {
|
||||
String firstLine = reader.readLine();
|
||||
return firstLine;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void finalize() {
|
||||
try {
|
||||
reader.close();
|
||||
System.out.println("Closed BufferedReader in the finalizer");
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package com.baeldung.finalkeyword;
|
||||
|
||||
public class BlackCat {
|
||||
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
package com.baeldung.finalkeyword;
|
||||
|
||||
public class BlackDog extends Dog {
|
||||
// public void sound() {
|
||||
// }
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package com.baeldung.finalkeyword;
|
||||
|
||||
public final class Cat {
|
||||
|
||||
private int weight;
|
||||
|
||||
public int getWeight() {
|
||||
return weight;
|
||||
}
|
||||
|
||||
public void setWeight(int weight) {
|
||||
this.weight = weight;
|
||||
}
|
||||
|
||||
public void methodWithFinalArguments(final int x) {
|
||||
// x=1;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
package com.baeldung.finalkeyword;
|
||||
|
||||
public class Dog {
|
||||
|
||||
public final void sound() {
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package com.baeldung.generics;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class Building {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(Building.class);
|
||||
|
||||
public void paint() {
|
||||
LOGGER.info("Painting Building");
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
package com.baeldung.generics;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class Generics {
|
||||
|
||||
// definition of a generic method
|
||||
public static <T> List<T> fromArrayToList(T[] a) {
|
||||
return Arrays.stream(a).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
// definition of a generic method
|
||||
public static <T, G> List<G> fromArrayToList(T[] a, Function<T, G> mapperFunction) {
|
||||
return Arrays.stream(a).map(mapperFunction).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
// example of a generic method that has Number as an upper bound for T
|
||||
public static <T extends Number> List<T> fromArrayToListWithUpperBound(T[] a) {
|
||||
return Arrays.stream(a).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
// example of a generic method with a wild card, this method can be used
|
||||
// with a list of any subtype of Building
|
||||
public static void paintAllBuildings(List<? extends Building> buildings) {
|
||||
buildings.forEach(Building::paint);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package com.baeldung.generics;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class House extends Building {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(House.class);
|
||||
|
||||
public void paint() {
|
||||
LOGGER.info("Painting House");
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package com.baeldung.hashcode.entities;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class User {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(User.class);
|
||||
private long id;
|
||||
private String name;
|
||||
private String email;
|
||||
|
||||
public User(long id, String name, String email) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null)
|
||||
return false;
|
||||
if (this.getClass() != o.getClass())
|
||||
return false;
|
||||
User user = (User) o;
|
||||
return id == user.id && (name.equals(user.name) && email.equals(user.email));
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int hash = 7;
|
||||
hash = 31 * hash + (int) id;
|
||||
hash = 31 * hash + (name == null ? 0 : name.hashCode());
|
||||
hash = 31 * hash + (email == null ? 0 : email.hashCode());
|
||||
logger.info("hashCode() method called - Computed hash: " + hash);
|
||||
return hash;
|
||||
}
|
||||
// getters and setters here
|
||||
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package com.baeldung.immutableobjects;
|
||||
|
||||
public final class Currency {
|
||||
|
||||
private final String value;
|
||||
|
||||
private Currency(String currencyValue) {
|
||||
value = currencyValue;
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public static Currency of(String value) {
|
||||
return new Currency(value);
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package com.baeldung.immutableobjects;
|
||||
|
||||
// 4. Immutability in Java
|
||||
public final class Money {
|
||||
private final double amount;
|
||||
private final Currency currency;
|
||||
|
||||
public Money(double amount, Currency currency) {
|
||||
this.amount = amount;
|
||||
this.currency = currency;
|
||||
}
|
||||
|
||||
public Currency getCurrency() {
|
||||
return currency;
|
||||
}
|
||||
|
||||
public double getAmount() {
|
||||
return amount;
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
package com.baeldung.inheritance;
|
||||
|
||||
public class ArmoredCar extends Car implements Floatable, Flyable{
|
||||
private int bulletProofWindows;
|
||||
private String model;
|
||||
|
||||
public void remoteStartCar() {
|
||||
// this vehicle can be started by using a remote control
|
||||
}
|
||||
|
||||
public String registerModel() {
|
||||
return model;
|
||||
}
|
||||
|
||||
public String getAValue() {
|
||||
return super.model; // returns value of model defined in base class Car
|
||||
// return this.model; // will return value of model defined in ArmoredCar
|
||||
// return model; // will return value of model defined in ArmoredCar
|
||||
}
|
||||
|
||||
public static String msg() {
|
||||
// return super.msg(); // this won't compile.
|
||||
return "ArmoredCar";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void floatOnWater() {
|
||||
System.out.println("I can float!");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fly() {
|
||||
System.out.println("I can fly!");
|
||||
}
|
||||
|
||||
public void aMethod() {
|
||||
// System.out.println(duration); // Won't compile
|
||||
System.out.println(Floatable.duration); // outputs 10
|
||||
System.out.println(Flyable.duration); // outputs 20
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package com.baeldung.inheritance;
|
||||
|
||||
public class BMW extends Car {
|
||||
public BMW() {
|
||||
super(5, "BMW");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return model;
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package com.baeldung.inheritance;
|
||||
|
||||
public class Car {
|
||||
private final int DEFAULT_WHEEL_COUNT = 5;
|
||||
private final String DEFAULT_MODEL = "Basic";
|
||||
|
||||
protected int wheels;
|
||||
protected String model;
|
||||
|
||||
public Car() {
|
||||
this.wheels = DEFAULT_WHEEL_COUNT;
|
||||
this.model = DEFAULT_MODEL;
|
||||
}
|
||||
|
||||
public Car(int wheels, String model) {
|
||||
this.wheels = wheels;
|
||||
this.model = model;
|
||||
}
|
||||
|
||||
public void start() {
|
||||
// Check essential parts
|
||||
// If okay, start.
|
||||
}
|
||||
public static int count = 10;
|
||||
public static String msg() {
|
||||
return "Car";
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return model;
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
package com.baeldung.inheritance;
|
||||
|
||||
public class Employee {
|
||||
private String name;
|
||||
private Car car;
|
||||
|
||||
public Employee(String name, Car car) {
|
||||
this.name = name;
|
||||
this.car = car;
|
||||
}
|
||||
|
||||
public Car getCar() {
|
||||
return car;
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package com.baeldung.inheritance;
|
||||
|
||||
public interface Floatable {
|
||||
int duration = 10;
|
||||
void floatOnWater();
|
||||
|
||||
default void repair() {
|
||||
System.out.println("Repairing Floatable object");
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package com.baeldung.inheritance;
|
||||
|
||||
public interface Flyable {
|
||||
int duration = 10;
|
||||
void fly();
|
||||
|
||||
/*
|
||||
* Commented
|
||||
*/
|
||||
//default void repair() {
|
||||
// System.out.println("Repairing Flyable object");
|
||||
//}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package com.baeldung.inheritance;
|
||||
|
||||
public class SpaceCar extends Car implements SpaceTraveller {
|
||||
@Override
|
||||
public void floatOnWater() {
|
||||
System.out.println("SpaceCar floating!");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fly() {
|
||||
System.out.println("SpaceCar flying!");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remoteControl() {
|
||||
System.out.println("SpaceCar being controlled remotely!");
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
package com.baeldung.inheritance;
|
||||
|
||||
public interface SpaceTraveller extends Floatable, Flyable {
|
||||
int duration = 10;
|
||||
void remoteControl();
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package com.baeldung.inheritancecomposition.application;
|
||||
|
||||
import com.baeldung.inheritancecomposition.model.Actress;
|
||||
import com.baeldung.inheritancecomposition.model.Computer;
|
||||
import com.baeldung.inheritancecomposition.model.StandardMemory;
|
||||
import com.baeldung.inheritancecomposition.model.Person;
|
||||
import com.baeldung.inheritancecomposition.model.StandardProcessor;
|
||||
import com.baeldung.inheritancecomposition.model.StandardSoundCard;
|
||||
import com.baeldung.inheritancecomposition.model.Waitress;
|
||||
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
Person person = new Person("John", "john@domain.com", 35);
|
||||
Waitress waitress = new Waitress("Mary", "mary@domain.com", 22);
|
||||
System.out.println(waitress.serveStarter("mixed salad"));
|
||||
System.out.println(waitress.serveMainCourse("steak"));
|
||||
System.out.println(waitress.serveDessert("cup of cofee"));
|
||||
Actress actress = new Actress("Susan", "susan@domain.com", 30);
|
||||
System.out.println(actress.readScript("Psycho"));
|
||||
System.out.println(actress.performRole());
|
||||
Computer computer = new Computer(new StandardProcessor("Intel I3"), new StandardMemory("Kingston", "1TB"));
|
||||
computer.setSoundCard(new StandardSoundCard("Generic Sound Card"));
|
||||
System.out.println(computer);
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
package com.baeldung.inheritancecomposition.model;
|
||||
|
||||
public class Actress extends Person {
|
||||
|
||||
public Actress(String name, String email, int age) {
|
||||
super(name, email, age);
|
||||
}
|
||||
|
||||
public String readScript(String movie) {
|
||||
return "Reading the script of " + movie;
|
||||
}
|
||||
|
||||
public String performRole() {
|
||||
return "Performing a role";
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
package com.baeldung.inheritancecomposition.model;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class Computer {
|
||||
|
||||
private Processor processor;
|
||||
private Memory memory;
|
||||
private SoundCard soundCard;
|
||||
|
||||
public Computer(Processor processor, Memory memory) {
|
||||
this.processor = processor;
|
||||
this.memory = memory;
|
||||
}
|
||||
|
||||
public void setSoundCard(SoundCard soundCard) {
|
||||
this.soundCard = soundCard;
|
||||
}
|
||||
|
||||
public Processor getProcessor() {
|
||||
return processor;
|
||||
}
|
||||
|
||||
public Memory getMemory() {
|
||||
return memory;
|
||||
}
|
||||
|
||||
public Optional<SoundCard> getSoundCard() {
|
||||
return Optional.ofNullable(soundCard);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Computer{" + "processor=" + processor + ", memory=" + memory + ", soundcard=" + soundCard +"}";
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
package com.baeldung.inheritancecomposition.model;
|
||||
|
||||
public interface Memory {
|
||||
|
||||
String getBrand();
|
||||
|
||||
String getSize();
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
package com.baeldung.inheritancecomposition.model;
|
||||
|
||||
public class Person {
|
||||
|
||||
private final String name;
|
||||
private final String email;
|
||||
private final int age;
|
||||
|
||||
public Person(String name, String email, int age) {
|
||||
this.name = name;
|
||||
this.email = email;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Person{" + "name=" + name + ", email=" + email + ", age=" + age + "}";
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
package com.baeldung.inheritancecomposition.model;
|
||||
|
||||
public interface Processor {
|
||||
|
||||
String getModel();
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
package com.baeldung.inheritancecomposition.model;
|
||||
|
||||
public interface SoundCard {
|
||||
|
||||
String getBrand();
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package com.baeldung.inheritancecomposition.model;
|
||||
|
||||
public class StandardMemory implements Memory {
|
||||
|
||||
private String brand;
|
||||
private String size;
|
||||
|
||||
public StandardMemory(String brand, String size) {
|
||||
this.brand = brand;
|
||||
this.size = size;
|
||||
}
|
||||
|
||||
public String getBrand() {
|
||||
return brand;
|
||||
}
|
||||
|
||||
public String getSize() {
|
||||
return size;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Memory{" + "brand=" + brand + ", size=" + size + "}";
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package com.baeldung.inheritancecomposition.model;
|
||||
|
||||
public class StandardProcessor implements Processor {
|
||||
|
||||
private String model;
|
||||
|
||||
public StandardProcessor(String model) {
|
||||
this.model = model;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getModel() {
|
||||
return model;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Processor{" + "model=" + model + "}";
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package com.baeldung.inheritancecomposition.model;
|
||||
|
||||
public class StandardSoundCard implements SoundCard {
|
||||
|
||||
private String brand;
|
||||
|
||||
public StandardSoundCard(String brand) {
|
||||
this.brand = brand;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getBrand() {
|
||||
return brand;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "SoundCard{" + "brand=" + brand + "}";
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package com.baeldung.inheritancecomposition.model;
|
||||
|
||||
public class Waitress extends Person {
|
||||
|
||||
public Waitress(String name, String email, int age) {
|
||||
super(name, email, age);
|
||||
}
|
||||
|
||||
public String serveStarter(String starter) {
|
||||
return "Serving a " + starter;
|
||||
}
|
||||
|
||||
public String serveMainCourse(String mainCourse) {
|
||||
return "Serving a " + mainCourse;
|
||||
}
|
||||
|
||||
public String serveDessert(String dessert) {
|
||||
return "Serving a " + dessert;
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
package com.baeldung.initializationguide;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class User implements Serializable, Cloneable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
static String forum;
|
||||
private String name;
|
||||
private int id;
|
||||
|
||||
{
|
||||
id = 0;
|
||||
System.out.println("Instance Initializer");
|
||||
}
|
||||
|
||||
static {
|
||||
forum = "Java";
|
||||
System.out.println("Static Initializer");
|
||||
}
|
||||
|
||||
public User(String name, int id) {
|
||||
super();
|
||||
this.name = name;
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public User() {
|
||||
System.out.println("Constructor");
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object clone() throws CloneNotSupportedException {
|
||||
return this;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
package com.baeldung.interfaces;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class CommaSeparatedCustomers implements Customer.List {
|
||||
|
||||
private List<Customer> customers = new ArrayList<Customer>();
|
||||
|
||||
@Override
|
||||
public void Add(Customer customer) {
|
||||
customers.add(customer);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getCustomerNames() {
|
||||
return customers.stream().map(customer -> customer.getName()).collect(Collectors.joining(","));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
package com.baeldung.interfaces;
|
||||
|
||||
public class Customer {
|
||||
public interface List {
|
||||
void Add(Customer customer);
|
||||
|
||||
String getCustomerNames();
|
||||
}
|
||||
|
||||
private String name;
|
||||
|
||||
public Customer(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
String getName() {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user