diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/balancedtree/RedBlackTree.java b/src/main/java/com/williamfiset/algorithms/datastructures/balancedtree/RedBlackTree.java index 4059d435b..393712eeb 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/balancedtree/RedBlackTree.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/balancedtree/RedBlackTree.java @@ -146,7 +146,7 @@ public boolean contains(T value) { public boolean insert(T val) { if (val == null) { - throw new IllegalArgumentException("Red-Black tree does not allow null values."); + throw new NullPointerException("Red-Black tree does not allow null values."); } Node x = root, y = NIL; diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/balancedtree/TreapTree.java b/src/main/java/com/williamfiset/algorithms/datastructures/balancedtree/TreapTree.java index 8bf8da810..1a5cd0a78 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/balancedtree/TreapTree.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/balancedtree/TreapTree.java @@ -93,7 +93,7 @@ public boolean isEmpty() { public boolean insert(T val, int priority) { if (val == null) { - throw new IllegalArgumentException("TreapTree does not allow null values"); + throw new NullPointerException("TreapTree does not allow null values"); } if (!contains(root, val)) { root = insert(this.root, val, priority); diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/binarysearchtree/SplayTree.java b/src/main/java/com/williamfiset/algorithms/datastructures/binarysearchtree/SplayTree.java index a2402ba85..05cbc9164 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/binarysearchtree/SplayTree.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/binarysearchtree/SplayTree.java @@ -6,6 +6,7 @@ import com.williamfiset.algorithms.datastructures.utils.TreePrinter; import java.util.ArrayList; +import java.util.Objects; import java.util.Scanner; /** @@ -30,13 +31,7 @@ public static class BinaryTree> implements TreePrinter.P private BinaryTree leftChild, rightChild; public BinaryTree(T data) { - if (data == null) { - try { - throw new Exception("Null data not allowed into tree"); - } catch (Exception e) { - e.printStackTrace(); - } - } else this.data = data; + this.data = Objects.requireNonNull(data); } @Override @@ -67,13 +62,7 @@ public T getData() { } public void setData(T data) { - if (data == null) { - try { - throw new Exception("Null data not allowed into tree"); - } catch (Exception e) { - e.printStackTrace(); - } - } else this.data = data; + this.data = Objects.requireNonNull(data); } @Override diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/dynamicarray/IntArray.java b/src/main/java/com/williamfiset/algorithms/datastructures/dynamicarray/IntArray.java index 623a5a87f..2c996dc0c 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/dynamicarray/IntArray.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/dynamicarray/IntArray.java @@ -22,14 +22,14 @@ public IntArray() { // Initialize the array with a certain capacity public IntArray(int capacity) { - if (capacity < 0) throw new IllegalArgumentException("Illegal Capacity: " + capacity); + if (capacity < 0) throw new NegativeArraySizeException("Illegal Capacity: " + capacity); this.capacity = capacity; arr = new int[capacity]; } // Given an array make it a dynamic array! public IntArray(int[] array) { - if (array == null) throw new IllegalArgumentException("Array cannot be null"); + if (array == null) throw new NullPointerException("Array cannot be null"); arr = java.util.Arrays.copyOf(array, array.length); capacity = len = array.length; } diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/fenwicktree/FenwickTreeRangeQueryPointUpdate.java b/src/main/java/com/williamfiset/algorithms/datastructures/fenwicktree/FenwickTreeRangeQueryPointUpdate.java index 3fa9c7205..a07f2a9d2 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/fenwicktree/FenwickTreeRangeQueryPointUpdate.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/fenwicktree/FenwickTreeRangeQueryPointUpdate.java @@ -23,7 +23,7 @@ public FenwickTreeRangeQueryPointUpdate(int sz) { // does not get used, O(n) construction. public FenwickTreeRangeQueryPointUpdate(long[] values) { - if (values == null) throw new IllegalArgumentException("Values array cannot be null!"); + if (values == null) throw new NullPointerException("Values array cannot be null!"); N = values.length; values[0] = 0L; diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/fenwicktree/FenwickTreeRangeUpdatePointQuery.java b/src/main/java/com/williamfiset/algorithms/datastructures/fenwicktree/FenwickTreeRangeUpdatePointQuery.java index bc38ab20b..277da4a1d 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/fenwicktree/FenwickTreeRangeUpdatePointQuery.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/fenwicktree/FenwickTreeRangeUpdatePointQuery.java @@ -22,7 +22,7 @@ public class FenwickTreeRangeUpdatePointQuery { // does not get used, O(n) construction. public FenwickTreeRangeUpdatePointQuery(long[] values) { - if (values == null) throw new IllegalArgumentException("Values array cannot be null!"); + if (values == null) throw new NullPointerException("Values array cannot be null!"); N = values.length; values[0] = 0L; diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/fibonacciheap/FibonacciHeap.java b/src/main/java/com/williamfiset/algorithms/datastructures/fibonacciheap/FibonacciHeap.java index 9b815dafd..e2333be37 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/fibonacciheap/FibonacciHeap.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/fibonacciheap/FibonacciHeap.java @@ -71,7 +71,7 @@ private void moveToRoot(FibonacciHeapNode node) { public boolean add(E e) { if (e == null) { - throw new IllegalArgumentException( + throw new NullPointerException( "Null elements not allowed in this FibonacciHeap implementation."); } diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/hashtable/DoubleHashingTestObject.java b/src/main/java/com/williamfiset/algorithms/datastructures/hashtable/DoubleHashingTestObject.java index f8a9513b4..dba9f6fb0 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/hashtable/DoubleHashingTestObject.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/hashtable/DoubleHashingTestObject.java @@ -6,6 +6,7 @@ */ package com.williamfiset.algorithms.datastructures.hashtable; +import java.util.Objects; import java.util.Random; public class DoubleHashingTestObject implements SecondaryHash { @@ -35,15 +36,13 @@ public DoubleHashingTestObject(int data) { } public DoubleHashingTestObject(int[] data) { - if (data == null) throw new IllegalArgumentException("Cannot be null"); - vectorData = data; + vectorData = Objects.requireNonNull(data); vectorHash(); computeHash(); } public DoubleHashingTestObject(String data) { - if (data == null) throw new IllegalArgumentException("Cannot be null"); - stringData = data; + stringData = Objects.requireNonNull(data); stringHash(); computeHash(); } diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableOpenAddressingBase.java b/src/main/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableOpenAddressingBase.java index 45996ef89..7469728c2 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableOpenAddressingBase.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableOpenAddressingBase.java @@ -172,7 +172,7 @@ protected static final int gcd(int a, int b) { // Place a key-value pair into the hash-table. If the value already // exists inside the hash-table then the value is updated. public V insert(K key, V val) { - if (key == null) throw new IllegalArgumentException("Null key"); + if (key == null) throw new NullPointerException("Null key"); if (usedBuckets >= threshold) resizeTable(); setupProbing(key); @@ -229,7 +229,7 @@ public V insert(K key, V val) { // Returns true/false on whether a given key exists within the hash-table public boolean hasKey(K key) { - if (key == null) throw new IllegalArgumentException("Null key"); + if (key == null) throw new NullPointerException("Null key"); setupProbing(key); final int offset = normalizeIndex(key.hashCode()); @@ -273,7 +273,7 @@ public boolean hasKey(K key) { // NOTE: returns null if the value is null AND also returns // null if the key does not exists. public V get(K key) { - if (key == null) throw new IllegalArgumentException("Null key"); + if (key == null) throw new NullPointerException("Null key"); setupProbing(key); final int offset = normalizeIndex(key.hashCode()); @@ -319,7 +319,7 @@ public V get(K key) { // NOTE: returns null if the value is null AND also returns // null if the key does not exists. public V remove(K key) { - if (key == null) throw new IllegalArgumentException("Null key"); + if (key == null) throw new NullPointerException("Null key"); setupProbing(key); final int offset = normalizeIndex(key.hashCode()); diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableSeparateChaining.java b/src/main/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableSeparateChaining.java index 5660a3a52..3fa919a34 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableSeparateChaining.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableSeparateChaining.java @@ -104,7 +104,7 @@ public V add(K key, V value) { public V insert(K key, V value) { - if (key == null) throw new IllegalArgumentException("Null key"); + if (key == null) throw new NullPointerException("Null key"); Entry newEntry = new Entry<>(key, value); int bucketIndex = normalizeIndex(newEntry.hash); return bucketInsertEntry(bucketIndex, newEntry); diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/kdtree/GeneralKDTree.java b/src/main/java/com/williamfiset/algorithms/datastructures/kdtree/GeneralKDTree.java index 150a78703..d7247f1e0 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/kdtree/GeneralKDTree.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/kdtree/GeneralKDTree.java @@ -185,7 +185,7 @@ private class KDNode> { private KDNode right; public KDNode(E[] coords) { - if (coords == null) throw new IllegalArgumentException("Error: Null coordinate set passed"); + if (coords == null) throw new NullPointerException("Error: Null coordinate set passed"); if (coords.length != k) throw new IllegalArgumentException( "Error: Expected " + k + "dimensions, but given " + coords.length); diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/linkedlist/DoublyLinkedList.java b/src/main/java/com/williamfiset/algorithms/datastructures/linkedlist/DoublyLinkedList.java index e8074bdef..7101d8dea 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/linkedlist/DoublyLinkedList.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/linkedlist/DoublyLinkedList.java @@ -78,9 +78,9 @@ public void addFirst(T elem) { } // Add an element at a specified index - public void addAt(int index, T data) throws Exception { + public void addAt(int index, T data) { if (index < 0 || index > size) { - throw new Exception("Illegal Index"); + throw new IndexOutOfBoundsException(index); } if (index == 0) { addFirst(data); @@ -105,20 +105,20 @@ public void addAt(int index, T data) throws Exception { // Check the value of the first node if it exists, O(1) public T peekFirst() { - if (isEmpty()) throw new RuntimeException("Empty list"); + if (isEmpty()) throw new IllegalStateException("Empty list"); return head.data; } // Check the value of the last node if it exists, O(1) public T peekLast() { - if (isEmpty()) throw new RuntimeException("Empty list"); + if (isEmpty()) throw new IllegalStateException("Empty list"); return tail.data; } // Remove the first value at the head of the linked list, O(1) public T removeFirst() { // Can't remove data from an empty list - if (isEmpty()) throw new RuntimeException("Empty list"); + if (isEmpty()) throw new IllegalStateException("Empty list"); // Extract the data at the head and move // the head pointer forwards one node @@ -139,7 +139,7 @@ public T removeFirst() { // Remove the last value at the tail of the linked list, O(1) public T removeLast() { // Can't remove data from an empty list - if (isEmpty()) throw new RuntimeException("Empty list"); + if (isEmpty()) throw new IllegalStateException("Empty list"); // Extract the data at the tail and move // the tail pointer backwards one node @@ -185,7 +185,7 @@ private T remove(Node node) { public T removeAt(int index) { // Make sure the index provided is valid if (index < 0 || index >= size) { - throw new IllegalArgumentException(); + throw new IndexOutOfBoundsException(index); } int i; diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/priorityqueue/BinaryHeap.java b/src/main/java/com/williamfiset/algorithms/datastructures/priorityqueue/BinaryHeap.java index 9d6789d1b..ff14b0f67 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/priorityqueue/BinaryHeap.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/priorityqueue/BinaryHeap.java @@ -8,6 +8,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; +import java.util.Objects; public class BinaryHeap> { @@ -90,9 +91,7 @@ public boolean contains(T elem) { // element must not be null, O(log(n)) public void add(T elem) { - if (elem == null) throw new IllegalArgumentException(); - - heap.add(elem); + heap.add(Objects.requireNonNull(elem)); int indexOfLastElem = size() - 1; swim(indexOfLastElem); diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/priorityqueue/BinaryHeapQuickRemovals.java b/src/main/java/com/williamfiset/algorithms/datastructures/priorityqueue/BinaryHeapQuickRemovals.java index 88029e1f7..5535a7497 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/priorityqueue/BinaryHeapQuickRemovals.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/priorityqueue/BinaryHeapQuickRemovals.java @@ -11,6 +11,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.TreeSet; @@ -106,9 +107,7 @@ public boolean contains(T elem) { // element must not be null, O(log(n)) public void add(T elem) { - if (elem == null) throw new IllegalArgumentException(); - - heap.add(elem); + heap.add(Objects.requireNonNull(elem)); int indexOfLastElem = size() - 1; mapAdd(elem, indexOfLastElem); diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/priorityqueue/MinDHeap.java b/src/main/java/com/williamfiset/algorithms/datastructures/priorityqueue/MinDHeap.java index 5268b851c..8ed9b67f4 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/priorityqueue/MinDHeap.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/priorityqueue/MinDHeap.java @@ -5,6 +5,8 @@ */ package com.williamfiset.algorithms.datastructures.priorityqueue; +import java.util.Objects; + @SuppressWarnings("unchecked") public class MinDHeap> { @@ -61,8 +63,7 @@ public T poll() { // Adds a none null element to the priority queue public void add(T elem) { - if (elem == null) throw new IllegalArgumentException("No null elements please :)"); - heap[sz] = elem; + heap[sz] = Objects.requireNonNull(elem); swim(sz); sz++; } diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/priorityqueue/MinIndexedDHeap.java b/src/main/java/com/williamfiset/algorithms/datastructures/priorityqueue/MinIndexedDHeap.java index a3b205a0d..8e6d36ddb 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/priorityqueue/MinIndexedDHeap.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/priorityqueue/MinIndexedDHeap.java @@ -18,6 +18,7 @@ import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; +import java.util.Objects; public class MinIndexedDHeap> { @@ -104,7 +105,7 @@ public T pollMinValue() { public void insert(int ki, T value) { if (contains(ki)) throw new IllegalArgumentException("index already exists; received: " + ki); - valueNotNullOrThrow(value); + Objects.requireNonNull(value); pm[ki] = sz; im[sz] = ki; values[ki] = value; @@ -218,20 +219,15 @@ private void isNotEmptyOrThrow() { private void keyExistsAndValueNotNullOrThrow(int ki, Object value) { keyExistsOrThrow(ki); - valueNotNullOrThrow(value); + Objects.requireNonNull(value); } private void keyExistsOrThrow(int ki) { if (!contains(ki)) throw new NoSuchElementException("Index does not exist; received: " + ki); } - private void valueNotNullOrThrow(Object value) { - if (value == null) throw new IllegalArgumentException("value cannot be null"); - } - private void keyInBoundsOrThrow(int ki) { - if (ki < 0 || ki >= N) - throw new IllegalArgumentException("Key index out of bounds; received: " + ki); + if (ki < 0 || ki >= N) throw new IndexOutOfBoundsException(ki); } /* Test functions */ diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/quadtree/QuadTree.java b/src/main/java/com/williamfiset/algorithms/datastructures/quadtree/QuadTree.java index 817965ba5..4f2c42f45 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/quadtree/QuadTree.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/quadtree/QuadTree.java @@ -76,8 +76,7 @@ class Node { // Construct a quad tree for a particular region. public Node(Rect region) { - if (region == null) throw new IllegalArgumentException("Illegal argument"); - this.region = region; + this.region = Objects.requireNonNull(region); X = new long[NUM_POINTS]; Y = new long[NUM_POINTS]; } diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/queue/ArrayQueue.java b/src/main/java/com/williamfiset/algorithms/datastructures/queue/ArrayQueue.java index 82be4bd4c..2f0737385 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/queue/ArrayQueue.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/queue/ArrayQueue.java @@ -1,5 +1,7 @@ package com.williamfiset.algorithms.datastructures.queue; +import java.util.NoSuchElementException; + /** * Besides the Generics, the loss of property of size is another difference between ArrayQueue and * IntQueue. The size of ArrayQueue is calculated by the formula, as are empty status and full @@ -27,7 +29,7 @@ public ArrayQueue(int capacity) { @Override public void offer(T elem) { if (isFull()) { - throw new RuntimeException("Queue is full"); + throw new IllegalStateException("Queue is full"); } data[rear++] = elem; rear = adjustIndex(rear, data.length); @@ -37,7 +39,7 @@ public void offer(T elem) { @SuppressWarnings("unchecked") public T poll() { if (isEmpty()) { - throw new RuntimeException("Queue is empty"); + throw new NoSuchElementException("Queue is empty"); } front = adjustIndex(front, data.length); return (T) data[front++]; @@ -47,7 +49,7 @@ public T poll() { @SuppressWarnings("unchecked") public T peek() { if (isEmpty()) { - throw new RuntimeException("Queue is empty"); + throw new NoSuchElementException("Queue is empty"); } front = adjustIndex(front, data.length); return (T) data[front]; diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/queue/IntQueue.java b/src/main/java/com/williamfiset/algorithms/datastructures/queue/IntQueue.java index 956fe39e7..c03ac33f5 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/queue/IntQueue.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/queue/IntQueue.java @@ -9,6 +9,8 @@ */ package com.williamfiset.algorithms.datastructures.queue; +import java.util.NoSuchElementException; + public class IntQueue implements Queue { private int[] data; @@ -35,7 +37,7 @@ public int size() { @Override public Integer peek() { if (isEmpty()) { - throw new RuntimeException("Queue is empty"); + throw new NoSuchElementException("Queue is empty"); } front = front % data.length; return data[front]; @@ -49,7 +51,7 @@ public boolean isFull() { @Override public void offer(Integer value) { if (isFull()) { - throw new RuntimeException("Queue too small!"); + throw new IllegalStateException("Queue too small!"); } data[end++] = value; size++; @@ -60,7 +62,7 @@ public void offer(Integer value) { @Override public Integer poll() { if (size == 0) { - throw new RuntimeException("Queue is empty"); + throw new NoSuchElementException("Queue is empty"); } size--; front = front % data.length; diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/queue/LinkedQueue.java b/src/main/java/com/williamfiset/algorithms/datastructures/queue/LinkedQueue.java index 14830d203..d2f097fda 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/queue/LinkedQueue.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/queue/LinkedQueue.java @@ -5,6 +5,8 @@ */ package com.williamfiset.algorithms.datastructures.queue; +import java.util.NoSuchElementException; + public class LinkedQueue implements Iterable, Queue { private java.util.LinkedList list = new java.util.LinkedList(); @@ -28,14 +30,14 @@ public boolean isEmpty() { // Peek the element at the front of the queue // The method throws an error is the queue is empty public T peek() { - if (isEmpty()) throw new RuntimeException("Queue Empty"); + if (isEmpty()) throw new NoSuchElementException("Queue Empty"); return list.peekFirst(); } // Poll an element from the front of the queue // The method throws an error is the queue is empty public T poll() { - if (isEmpty()) throw new RuntimeException("Queue Empty"); + if (isEmpty()) throw new NoSuchElementException("Queue Empty"); return list.removeFirst(); } diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/GenericSegmentTree.java b/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/GenericSegmentTree.java index faba5b78e..3bbe0c8fa 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/GenericSegmentTree.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/GenericSegmentTree.java @@ -169,13 +169,13 @@ public GenericSegmentTree( SegmentCombinationFn segmentCombinationFunction, RangeUpdateFn rangeUpdateFunction) { if (values == null) { - throw new IllegalArgumentException("Segment tree values cannot be null."); + throw new NullPointerException("Segment tree values cannot be null."); } if (segmentCombinationFunction == null) { - throw new IllegalArgumentException("Please specify a valid segment combination function."); + throw new NullPointerException("Please specify a valid segment combination function."); } if (rangeUpdateFunction == null) { - throw new IllegalArgumentException("Please specify a valid range update function."); + throw new NullPointerException("Please specify a valid range update function."); } n = values.length; diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/GenericSegmentTree2.java b/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/GenericSegmentTree2.java index 02dc3de9c..32d88a257 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/GenericSegmentTree2.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/GenericSegmentTree2.java @@ -197,13 +197,13 @@ public GenericSegmentTree2( SegmentCombinationFn segmentCombinationFunction, RangeUpdateFn rangeUpdateFunction) { if (values == null) { - throw new IllegalArgumentException("Segment tree values cannot be null."); + throw new NullPointerException("Segment tree values cannot be null."); } if (segmentCombinationFunction == null) { - throw new IllegalArgumentException("Please specify a valid segment combination function."); + throw new NullPointerException("Please specify a valid segment combination function."); } if (rangeUpdateFunction == null) { - throw new IllegalArgumentException("Please specify a valid range update function."); + throw new NullPointerException("Please specify a valid range update function."); } n = values.length; diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/GenericSegmentTree3.java b/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/GenericSegmentTree3.java index db529d742..6d2f8c514 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/GenericSegmentTree3.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/GenericSegmentTree3.java @@ -251,13 +251,13 @@ public class GenericSegmentTree3 { // SegmentCombinationFn segmentCombinationFunction, // RangeUpdateFn rangeUpdateFunction) { // if (values == null) { - // throw new IllegalArgumentException("Segment tree values cannot be null."); + // throw new NullPointerException("Segment tree values cannot be null."); // } // if (segmentCombinationFunction == null) { - // throw new IllegalArgumentException("Please specify a valid segment combination function."); + // throw new NullPointerException("Please specify a valid segment combination function."); // } // if (rangeUpdateFunction == null) { - // throw new IllegalArgumentException("Please specify a valid range update function."); + // throw new NullPointerException("Please specify a valid range update function."); // } // n = values.length; diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/MaxQuerySumUpdateSegmentTree.java b/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/MaxQuerySumUpdateSegmentTree.java index e2628b65c..ac7ba0d6e 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/MaxQuerySumUpdateSegmentTree.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/MaxQuerySumUpdateSegmentTree.java @@ -42,7 +42,7 @@ private Long minSegmentUpdateFn(long base, int tl, int tr, long x) { public MaxQuerySumUpdateSegmentTree(long[] values) { if (values == null) { - throw new IllegalArgumentException("Segment tree values cannot be null."); + throw new NullPointerException("Segment tree values cannot be null."); } n = values.length; diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/MinQueryAssignUpdateSegmentTree.java b/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/MinQueryAssignUpdateSegmentTree.java index 3e233f8f3..56b50f1de 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/MinQueryAssignUpdateSegmentTree.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/MinQueryAssignUpdateSegmentTree.java @@ -32,7 +32,7 @@ private Long minFunction(Long a, Long b) { public MinQueryAssignUpdateSegmentTree(long[] values) { if (values == null) { - throw new IllegalArgumentException("Segment tree values cannot be null."); + throw new NullPointerException("Segment tree values cannot be null."); } n = values.length; diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/MinQuerySumUpdateSegmentTree.java b/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/MinQuerySumUpdateSegmentTree.java index b3eb68f61..a18e2ea86 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/MinQuerySumUpdateSegmentTree.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/MinQuerySumUpdateSegmentTree.java @@ -43,7 +43,7 @@ private Long minSegmentUpdateFn(long base, int tl, int tr, long x) { public MinQuerySumUpdateSegmentTree(long[] values) { if (values == null) { - throw new IllegalArgumentException("Segment tree values cannot be null."); + throw new NullPointerException("Segment tree values cannot be null."); } n = values.length; diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/Node.java b/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/Node.java index 00279ac4f..6ef247100 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/Node.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/Node.java @@ -19,7 +19,7 @@ public class Node { int minPos, maxPos, min = 0, sum = 0, lazy = 0; public Node(int[] values) { - if (values == null) throw new IllegalArgumentException("Null input to segment tree."); + if (values == null) throw new NullPointerException("Null input to segment tree."); buildTree(0, values.length); for (int i = 0; i < values.length; i++) { update(i, i + 1, values[i]); diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/RangeQueryPointUpdateSegmentTree.java b/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/RangeQueryPointUpdateSegmentTree.java index 757e3e214..612227606 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/RangeQueryPointUpdateSegmentTree.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/RangeQueryPointUpdateSegmentTree.java @@ -68,13 +68,13 @@ public RangeQueryPointUpdateSegmentTree( SegmentCombinationFn segmentCombinationFunction, RangeUpdateFn rangeUpdateFunction) { if (values == null) { - throw new IllegalArgumentException("Segment tree values cannot be null."); + throw new NullPointerException("Segment tree values cannot be null."); } if (segmentCombinationFunction == null) { - throw new IllegalArgumentException("Please specify a valid segment combination function."); + throw new NullPointerException("Please specify a valid segment combination function."); } if (rangeUpdateFunction == null) { - throw new IllegalArgumentException("Please specify a valid range update function."); + throw new NullPointerException("Please specify a valid range update function."); } n = values.length; this.segmentCombinationFn = segmentCombinationFunction; diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/SumQueryAssignUpdateSegmentTree.java b/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/SumQueryAssignUpdateSegmentTree.java index 015a8835c..db77c8e7b 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/SumQueryAssignUpdateSegmentTree.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/SumQueryAssignUpdateSegmentTree.java @@ -38,7 +38,7 @@ private Long sumRangeUpdateAssignFn(long base, int tl, int tr, long x) { public SumQueryAssignUpdateSegmentTree(long[] values) { if (values == null) { - throw new IllegalArgumentException("Segment tree values cannot be null."); + throw new NullPointerException("Segment tree values cannot be null."); } n = values.length; diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/SumQueryMultiplicationUpdateSegmentTree.java b/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/SumQueryMultiplicationUpdateSegmentTree.java index 4f2428eec..abecbdd1c 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/SumQueryMultiplicationUpdateSegmentTree.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/SumQueryMultiplicationUpdateSegmentTree.java @@ -52,7 +52,7 @@ private long multLruf(Long delta1, Long delta2) { public SumQueryMultiplicationUpdateSegmentTree(long[] values) { if (values == null) { - throw new IllegalArgumentException("Segment tree values cannot be null."); + throw new NullPointerException("Segment tree values cannot be null."); } n = values.length; diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/SumQuerySumUpdateSegmentTree.java b/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/SumQuerySumUpdateSegmentTree.java index dc3498008..dea61713f 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/SumQuerySumUpdateSegmentTree.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/segmenttree/SumQuerySumUpdateSegmentTree.java @@ -32,7 +32,7 @@ private Long sumFunction(Long a, Long b) { public SumQuerySumUpdateSegmentTree(long[] values) { if (values == null) { - throw new IllegalArgumentException("Segment tree values cannot be null."); + throw new NullPointerException("Segment tree values cannot be null."); } n = values.length; diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/stack/ArrayStack.java b/src/main/java/com/williamfiset/algorithms/datastructures/stack/ArrayStack.java index a831c4ca8..346623f76 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/stack/ArrayStack.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/stack/ArrayStack.java @@ -1,7 +1,7 @@ package com.williamfiset.algorithms.datastructures.stack; import java.util.Arrays; -import java.util.EmptyStackException; +import java.util.NoSuchElementException; /** * @author liujingkun @@ -43,7 +43,7 @@ private void increaseCapacity() { @Override @SuppressWarnings("unchecked") public T pop() { - if (isEmpty()) throw new EmptyStackException(); + if (isEmpty()) throw new NoSuchElementException(); T elem = (T) data[--size]; data[size] = null; return elem; @@ -52,7 +52,7 @@ public T pop() { @Override @SuppressWarnings("unchecked") public T peek() { - if (isEmpty()) throw new EmptyStackException(); + if (isEmpty()) throw new NoSuchElementException(); return (T) data[size - 1]; } } diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/stack/ListStack.java b/src/main/java/com/williamfiset/algorithms/datastructures/stack/ListStack.java index 244d8e185..f9fdab6ef 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/stack/ListStack.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/stack/ListStack.java @@ -5,6 +5,8 @@ */ package com.williamfiset.algorithms.datastructures.stack; +import java.util.NoSuchElementException; + public class ListStack implements Iterable, Stack { private java.util.LinkedList list = new java.util.LinkedList(); @@ -35,14 +37,14 @@ public void push(T elem) { // Pop an element off the stack // Throws an error is the stack is empty public T pop() { - if (isEmpty()) throw new java.util.EmptyStackException(); + if (isEmpty()) throw new NoSuchElementException(); return list.removeLast(); } // Peek the top of the stack without removing an element // Throws an exception if the stack is empty public T peek() { - if (isEmpty()) throw new java.util.EmptyStackException(); + if (isEmpty()) throw new NoSuchElementException(); return list.peekLast(); } diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/suffixarray/SuffixArray.java b/src/main/java/com/williamfiset/algorithms/datastructures/suffixarray/SuffixArray.java index 77b5c498a..a99a9555e 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/suffixarray/SuffixArray.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/suffixarray/SuffixArray.java @@ -5,6 +5,8 @@ */ package com.williamfiset.algorithms.datastructures.suffixarray; +import java.util.Objects; + public abstract class SuffixArray { // Length of the suffix array @@ -23,8 +25,7 @@ public abstract class SuffixArray { private boolean constructedLcpArray = false; public SuffixArray(int[] text) { - if (text == null) throw new IllegalArgumentException("Text cannot be null."); - this.T = text; + this.T = Objects.requireNonNull(text); this.N = text.length; } diff --git a/src/main/java/com/williamfiset/algorithms/datastructures/trie/Trie.java b/src/main/java/com/williamfiset/algorithms/datastructures/trie/Trie.java index 74f5af7ed..8527556e4 100644 --- a/src/main/java/com/williamfiset/algorithms/datastructures/trie/Trie.java +++ b/src/main/java/com/williamfiset/algorithms/datastructures/trie/Trie.java @@ -27,7 +27,7 @@ public void addChild(Node node, char c) { // contains a prefix already in the trie public boolean insert(String key, int numInserts) { - if (key == null) throw new IllegalArgumentException("Null not permitted in trie"); + if (key == null) throw new NullPointerException("Null not permitted in trie"); if (numInserts <= 0) throw new IllegalArgumentException("numInserts has to be greater than zero"); @@ -114,7 +114,7 @@ public boolean contains(String key) { // Returns the count of a particular prefix public int count(String key) { - if (key == null) throw new IllegalArgumentException("Null not permitted"); + if (key == null) throw new NullPointerException("Null not permitted"); Node node = root; diff --git a/src/main/java/com/williamfiset/algorithms/dp/CoinChange.java b/src/main/java/com/williamfiset/algorithms/dp/CoinChange.java index 5daa688d7..fc43486bf 100644 --- a/src/main/java/com/williamfiset/algorithms/dp/CoinChange.java +++ b/src/main/java/com/williamfiset/algorithms/dp/CoinChange.java @@ -32,7 +32,7 @@ public static class Solution { private static final int INF = Integer.MAX_VALUE / 2; public static Solution coinChange(int[] coins, final int n) { - if (coins == null) throw new IllegalArgumentException("Coins array is null"); + if (coins == null) throw new NullPointerException("Coins array is null"); if (coins.length == 0) throw new IllegalArgumentException("No coin values :/"); for (int coin : coins) { if (coin <= 0) { @@ -86,7 +86,7 @@ public static Solution coinChange(int[] coins, final int n) { } public static Solution coinChangeSpaceEfficient(int[] coins, int n) { - if (coins == null) throw new IllegalArgumentException("Coins array is null"); + if (coins == null) throw new NullPointerException("Coins array is null"); // Initialize table and set everything to infinity except first cell int[] dp = new int[n + 1]; @@ -135,7 +135,7 @@ public static Solution coinChangeSpaceEfficient(int[] coins, int n) { // all possible states like the tabular approach does. This can speedup // things especially if the coin denominations are large. public static int coinChangeRecursive(int[] coins, int n) { - if (coins == null) throw new IllegalArgumentException("Coins array is null"); + if (coins == null) throw new NullPointerException("Coins array is null"); if (n < 0) return -1; int[] dp = new int[n + 1]; diff --git a/src/main/java/com/williamfiset/algorithms/dp/EditDistanceRecursive.java b/src/main/java/com/williamfiset/algorithms/dp/EditDistanceRecursive.java index bb79e33b5..71f41b756 100644 --- a/src/main/java/com/williamfiset/algorithms/dp/EditDistanceRecursive.java +++ b/src/main/java/com/williamfiset/algorithms/dp/EditDistanceRecursive.java @@ -7,6 +7,8 @@ */ package com.williamfiset.algorithms.dp; +import java.util.Objects; + public class EditDistanceRecursive { final char[] a, b; @@ -14,11 +16,8 @@ public class EditDistanceRecursive { public EditDistanceRecursive( String a, String b, int insertionCost, int deletionCost, int substitutionCost) { - if (a == null || b == null) { - throw new IllegalArgumentException("Input string must not be null"); - } - this.a = a.toCharArray(); - this.b = b.toCharArray(); + this.a = Objects.requireNonNull(a).toCharArray(); + this.b = Objects.requireNonNull(b).toCharArray(); this.insertionCost = insertionCost; this.deletionCost = deletionCost; this.substitutionCost = substitutionCost; diff --git a/src/main/java/com/williamfiset/algorithms/dp/KnapsackUnbounded.java b/src/main/java/com/williamfiset/algorithms/dp/KnapsackUnbounded.java index 116d2ed1a..32e9ea4f7 100644 --- a/src/main/java/com/williamfiset/algorithms/dp/KnapsackUnbounded.java +++ b/src/main/java/com/williamfiset/algorithms/dp/KnapsackUnbounded.java @@ -13,6 +13,8 @@ */ package com.williamfiset.algorithms.dp; +import java.util.Objects; + public class KnapsackUnbounded { /** @@ -24,7 +26,7 @@ public class KnapsackUnbounded { */ public static int unboundedKnapsack(int maxWeight, int[] W, int[] V) { - if (W == null || V == null || W.length != V.length || maxWeight < 0) + if (Objects.requireNonNull(W).length != Objects.requireNonNull(V).length || maxWeight < 0) throw new IllegalArgumentException("Invalid input"); final int N = W.length; @@ -56,7 +58,7 @@ public static int unboundedKnapsack(int maxWeight, int[] W, int[] V) { public static int unboundedKnapsackSpaceEfficient(int maxWeight, int[] W, int[] V) { - if (W == null || V == null || W.length != V.length) + if (Objects.requireNonNull(W).length != Objects.requireNonNull(V).length) throw new IllegalArgumentException("Invalid input"); final int N = W.length; diff --git a/src/main/java/com/williamfiset/algorithms/dp/Knapsack_01.java b/src/main/java/com/williamfiset/algorithms/dp/Knapsack_01.java index 8cea8b26a..9e6ff434f 100644 --- a/src/main/java/com/williamfiset/algorithms/dp/Knapsack_01.java +++ b/src/main/java/com/williamfiset/algorithms/dp/Knapsack_01.java @@ -13,6 +13,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.Objects; public class Knapsack_01 { @@ -25,7 +26,7 @@ public class Knapsack_01 { */ public static int knapsack(int capacity, int[] W, int[] V) { - if (W == null || V == null || W.length != V.length || capacity < 0) + if (Objects.requireNonNull(W).length != Objects.requireNonNull(V).length || capacity < 0) throw new IllegalArgumentException("Invalid input"); final int N = W.length; diff --git a/src/main/java/com/williamfiset/algorithms/dp/MinimumWeightPerfectMatching.java b/src/main/java/com/williamfiset/algorithms/dp/MinimumWeightPerfectMatching.java index 6d3ed625e..d05fc45fc 100644 --- a/src/main/java/com/williamfiset/algorithms/dp/MinimumWeightPerfectMatching.java +++ b/src/main/java/com/williamfiset/algorithms/dp/MinimumWeightPerfectMatching.java @@ -32,7 +32,7 @@ public class MinimumWeightPerfectMatching { // The cost matrix should be a symmetric (i.e cost[i][j] = cost[j][i]) public MinimumWeightPerfectMatching(double[][] cost) { - if (cost == null) throw new IllegalArgumentException("Input cannot be null"); + this.cost = Objects.requireNonNull(cost); n = cost.length; if (n == 0) throw new IllegalArgumentException("Matrix size is zero"); if (n % 2 != 0) @@ -42,7 +42,6 @@ public MinimumWeightPerfectMatching(double[][] cost) { "Matrix too large! A matrix that size for the MWPM problem with a time complexity of" + "O(n^2*2^n) requires way too much computation and memory for a modern home computer."); END_STATE = (1 << n) - 1; - this.cost = cost; } public double getMinWeightCost() { diff --git a/src/main/java/com/williamfiset/algorithms/dp/WeightedMaximumCardinalityMatchingIterative.java b/src/main/java/com/williamfiset/algorithms/dp/WeightedMaximumCardinalityMatchingIterative.java index 2198e1fba..e708c8fe4 100644 --- a/src/main/java/com/williamfiset/algorithms/dp/WeightedMaximumCardinalityMatchingIterative.java +++ b/src/main/java/com/williamfiset/algorithms/dp/WeightedMaximumCardinalityMatchingIterative.java @@ -33,7 +33,7 @@ public class WeightedMaximumCardinalityMatchingIterative implements MwpmInterfac // The cost matrix should be a symmetric (i.e cost[i][j] = cost[j][i]) public WeightedMaximumCardinalityMatchingIterative(double[][] cost) { - if (cost == null) throw new IllegalArgumentException("Input cannot be null"); + this.cost = Objects.requireNonNull(cost); n = cost.length; if (n == 0) throw new IllegalArgumentException("Matrix size is zero"); if (n % 2 != 0) @@ -43,7 +43,6 @@ public WeightedMaximumCardinalityMatchingIterative(double[][] cost) { "Matrix too large! A matrix that size for the MWPM problem with a time complexity of" + "O(n^2*2^n) requires way too much computation and memory for a modern home computer."); END_STATE = (1 << n) - 1; - this.cost = cost; } public double getMinWeightCost() { diff --git a/src/main/java/com/williamfiset/algorithms/dp/WeightedMaximumCardinalityMatchingRecursive.java b/src/main/java/com/williamfiset/algorithms/dp/WeightedMaximumCardinalityMatchingRecursive.java index d3dc1a1d7..e36c3bc1a 100644 --- a/src/main/java/com/williamfiset/algorithms/dp/WeightedMaximumCardinalityMatchingRecursive.java +++ b/src/main/java/com/williamfiset/algorithms/dp/WeightedMaximumCardinalityMatchingRecursive.java @@ -87,8 +87,7 @@ public String toString() { // The cost matrix should be a symmetric (i.e cost[i][j] = cost[j][i]) and have a cost of `null` // between nodes i and j if no edge exists between those two nodes. public WeightedMaximumCardinalityMatchingRecursive(Double[][] cost) { - if (cost == null) throw new IllegalArgumentException("Input cannot be null"); - n = cost.length; + n = Objects.requireNonNull(cost).length; if (n <= 1) throw new IllegalArgumentException("Invalid matrix size: " + n); setCostMatrix(cost); FULL_STATE = (1 << n) - 1; diff --git a/src/main/java/com/williamfiset/algorithms/dp/examples/editdistance/EditDistance.java b/src/main/java/com/williamfiset/algorithms/dp/examples/editdistance/EditDistance.java index c018f9bb3..ea0ed5810 100644 --- a/src/main/java/com/williamfiset/algorithms/dp/examples/editdistance/EditDistance.java +++ b/src/main/java/com/williamfiset/algorithms/dp/examples/editdistance/EditDistance.java @@ -10,11 +10,8 @@ public class EditDistance { public EditDistance( String a, String b, int insertionCost, int deletionCost, int substitutionCost) { - if (a == null || b == null) { - throw new IllegalArgumentException("Input string must not be null"); - } - this.a = a.toCharArray(); - this.b = b.toCharArray(); + this.a = Objects.requireNonNull(a).toCharArray(); + this.b = Objects.requireNonNull(b).toCharArray(); this.insertionCost = insertionCost; this.deletionCost = deletionCost; this.substitutionCost = substitutionCost; diff --git a/src/main/java/com/williamfiset/algorithms/geometry/CollinearPoints.java b/src/main/java/com/williamfiset/algorithms/geometry/CollinearPoints.java index dd7521b9d..fdcd69792 100644 --- a/src/main/java/com/williamfiset/algorithms/geometry/CollinearPoints.java +++ b/src/main/java/com/williamfiset/algorithms/geometry/CollinearPoints.java @@ -11,6 +11,7 @@ import static java.lang.Math.*; import java.awt.geom.Point2D; +import java.util.Objects; public class CollinearPoints { @@ -24,6 +25,10 @@ public class CollinearPoints { // and facing point b. public static int collinear(Point2D a, Point2D b, Point2D c) { + Objects.requireNonNull(a); + Objects.requireNonNull(b); + Objects.requireNonNull(c); + if (a.distance(b) < EPS) throw new IllegalArgumentException("a cannot equal b"); // To determine if c is on the line we will use the determinant of diff --git a/src/main/java/com/williamfiset/algorithms/geometry/ConvexPolygonArea.java b/src/main/java/com/williamfiset/algorithms/geometry/ConvexPolygonArea.java index d037b4bfe..eba903467 100644 --- a/src/main/java/com/williamfiset/algorithms/geometry/ConvexPolygonArea.java +++ b/src/main/java/com/williamfiset/algorithms/geometry/ConvexPolygonArea.java @@ -9,6 +9,7 @@ package com.williamfiset.algorithms.geometry; import java.awt.geom.Point2D; +import java.util.Objects; public class ConvexPolygonArea { @@ -17,7 +18,7 @@ public class ConvexPolygonArea { // method is an array of N+1 points where points[0] = points[N] public static double convexPolygonArea(Point2D[] points) { - int N = points.length - 1; + int N = Objects.requireNonNull(points).length - 1; if (N < 3 || points[0] != points[N]) throw new IllegalArgumentException( diff --git a/src/main/java/com/williamfiset/algorithms/geometry/PointInsideTriangle.java b/src/main/java/com/williamfiset/algorithms/geometry/PointInsideTriangle.java index cd2ac38f2..bd780de07 100644 --- a/src/main/java/com/williamfiset/algorithms/geometry/PointInsideTriangle.java +++ b/src/main/java/com/williamfiset/algorithms/geometry/PointInsideTriangle.java @@ -11,6 +11,7 @@ import static java.lang.Math.*; import java.awt.geom.Point2D; +import java.util.Objects; public class PointInsideTriangle { @@ -60,6 +61,9 @@ public static boolean pointInsideTriangle2(Point2D a, Point2D b, Point2D c, Poin // to the left from the frame of reference of standing at point a // and facing point b. private static int collinear(Point2D a, Point2D b, Point2D c) { + Objects.requireNonNull(a); + Objects.requireNonNull(b); + Objects.requireNonNull(c); double ax = a.getX(), ay = a.getY(); double bx = b.getX(), by = b.getY(); double cx = c.getX(), cy = c.getY(); diff --git a/src/main/java/com/williamfiset/algorithms/graphtheory/ArticulationPointsAdjacencyList.java b/src/main/java/com/williamfiset/algorithms/graphtheory/ArticulationPointsAdjacencyList.java index ea4cf20cf..2de9a2716 100644 --- a/src/main/java/com/williamfiset/algorithms/graphtheory/ArticulationPointsAdjacencyList.java +++ b/src/main/java/com/williamfiset/algorithms/graphtheory/ArticulationPointsAdjacencyList.java @@ -12,6 +12,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.Objects; public class ArticulationPointsAdjacencyList { @@ -22,7 +23,7 @@ public class ArticulationPointsAdjacencyList { private List> graph; public ArticulationPointsAdjacencyList(List> graph, int n) { - if (graph == null || n <= 0 || graph.size() != n) throw new IllegalArgumentException(); + if (n <= 0 || Objects.requireNonNull(graph).size() != n) throw new IllegalArgumentException(); this.graph = graph; this.n = n; } diff --git a/src/main/java/com/williamfiset/algorithms/graphtheory/Boruvkas.java b/src/main/java/com/williamfiset/algorithms/graphtheory/Boruvkas.java index 1be3a5f7d..fc173ea36 100644 --- a/src/main/java/com/williamfiset/algorithms/graphtheory/Boruvkas.java +++ b/src/main/java/com/williamfiset/algorithms/graphtheory/Boruvkas.java @@ -44,8 +44,7 @@ public int compareTo(Edge other) { private List mst; public Boruvkas(int n, int m, Edge[] graph) { - if (graph == null) throw new IllegalArgumentException(); - this.graph = graph; + this.graph = Objects.requireNonNull(graph); this.n = n; this.m = m; } diff --git a/src/main/java/com/williamfiset/algorithms/graphtheory/BreadthFirstSearchAdjacencyListIterative.java b/src/main/java/com/williamfiset/algorithms/graphtheory/BreadthFirstSearchAdjacencyListIterative.java index 3ca3d1898..6670bb001 100644 --- a/src/main/java/com/williamfiset/algorithms/graphtheory/BreadthFirstSearchAdjacencyListIterative.java +++ b/src/main/java/com/williamfiset/algorithms/graphtheory/BreadthFirstSearchAdjacencyListIterative.java @@ -12,6 +12,7 @@ import java.util.Collections; import java.util.Deque; import java.util.List; +import java.util.Objects; public class BreadthFirstSearchAdjacencyListIterative { @@ -30,9 +31,8 @@ public Edge(int from, int to, int cost) { private List> graph; public BreadthFirstSearchAdjacencyListIterative(List> graph) { - if (graph == null) throw new IllegalArgumentException("Graph can not be null"); + this.graph = Objects.requireNonNull(graph); n = graph.size(); - this.graph = graph; } /** diff --git a/src/main/java/com/williamfiset/algorithms/graphtheory/BridgesAdjacencyList.java b/src/main/java/com/williamfiset/algorithms/graphtheory/BridgesAdjacencyList.java index 49151169e..12e85186f 100644 --- a/src/main/java/com/williamfiset/algorithms/graphtheory/BridgesAdjacencyList.java +++ b/src/main/java/com/williamfiset/algorithms/graphtheory/BridgesAdjacencyList.java @@ -12,6 +12,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.Objects; public class BridgesAdjacencyList { @@ -23,8 +24,8 @@ public class BridgesAdjacencyList { private List bridges; public BridgesAdjacencyList(List> graph, int n) { - if (graph == null || n <= 0 || graph.size() != n) throw new IllegalArgumentException(); - this.graph = graph; + this.graph = Objects.requireNonNull(graph); + if (n <= 0 || graph.size() != n) throw new IllegalArgumentException(); this.n = n; } diff --git a/src/main/java/com/williamfiset/algorithms/graphtheory/BridgesAdjacencyListIterative.java b/src/main/java/com/williamfiset/algorithms/graphtheory/BridgesAdjacencyListIterative.java index 0fb3d5b7c..b735ae24e 100644 --- a/src/main/java/com/williamfiset/algorithms/graphtheory/BridgesAdjacencyListIterative.java +++ b/src/main/java/com/williamfiset/algorithms/graphtheory/BridgesAdjacencyListIterative.java @@ -24,8 +24,8 @@ public class BridgesAdjacencyListIterative { private static int CALLBACK_TOKEN = -2; public BridgesAdjacencyListIterative(List> graph, int n) { - if (graph == null || n <= 0 || graph.size() != n) throw new IllegalArgumentException(); - this.graph = graph; + this.graph = Objects.requireNonNull(graph); + if (n <= 0 || graph.size() != n) throw new IllegalArgumentException(); this.n = n; } diff --git a/src/main/java/com/williamfiset/algorithms/graphtheory/ChinesePostmanProblem.java b/src/main/java/com/williamfiset/algorithms/graphtheory/ChinesePostmanProblem.java index 341888441..b5787d3d7 100644 --- a/src/main/java/com/williamfiset/algorithms/graphtheory/ChinesePostmanProblem.java +++ b/src/main/java/com/williamfiset/algorithms/graphtheory/ChinesePostmanProblem.java @@ -224,7 +224,7 @@ public String toString() { // The cost matrix should be a symmetric (i.e cost[i][j] = cost[j][i]) and have a cost of `null` // between nodes i and j if no edge exists between those two nodes. public WeightedMaximumCardinalityMatchingRecursive(Double[][] cost) { - if (cost == null) throw new IllegalArgumentException("Input cannot be null"); + Objects.requireNonNull(cost); n = cost.length; if (n <= 1) throw new IllegalArgumentException("Invalid matrix size: " + n); setCostMatrix(cost); @@ -412,9 +412,8 @@ private static class EulerianPathDirectedEdgesAdjacencyList { private List> graph; public EulerianPathDirectedEdgesAdjacencyList(List> graph) { - if (graph == null) throw new IllegalArgumentException("Graph cannot be null"); + this.graph = Objects.requireNonNull(graph); n = graph.size(); - this.graph = graph; path = new LinkedList<>(); } diff --git a/src/main/java/com/williamfiset/algorithms/graphtheory/ConnectedComponentsDfsSolverAdjacencyList.java b/src/main/java/com/williamfiset/algorithms/graphtheory/ConnectedComponentsDfsSolverAdjacencyList.java index 827945121..c5ffda66a 100644 --- a/src/main/java/com/williamfiset/algorithms/graphtheory/ConnectedComponentsDfsSolverAdjacencyList.java +++ b/src/main/java/com/williamfiset/algorithms/graphtheory/ConnectedComponentsDfsSolverAdjacencyList.java @@ -23,9 +23,8 @@ public class ConnectedComponentsDfsSolverAdjacencyList { * @param graph - An undirected graph as an adjacency list. */ public ConnectedComponentsDfsSolverAdjacencyList(List> graph) { - if (graph == null) throw new NullPointerException(); + this.graph = Objects.requireNonNull(graph); this.n = graph.size(); - this.graph = graph; } public int[] getComponents() { diff --git a/src/main/java/com/williamfiset/algorithms/graphtheory/DijkstrasShortestPathAdjacencyList.java b/src/main/java/com/williamfiset/algorithms/graphtheory/DijkstrasShortestPathAdjacencyList.java index f1639bc04..12003e0ec 100644 --- a/src/main/java/com/williamfiset/algorithms/graphtheory/DijkstrasShortestPathAdjacencyList.java +++ b/src/main/java/com/williamfiset/algorithms/graphtheory/DijkstrasShortestPathAdjacencyList.java @@ -14,6 +14,7 @@ import java.util.Collections; import java.util.Comparator; import java.util.List; +import java.util.Objects; import java.util.PriorityQueue; public class DijkstrasShortestPathAdjacencyList { @@ -72,8 +73,7 @@ public DijkstrasShortestPathAdjacencyList(int n) { public DijkstrasShortestPathAdjacencyList(int n, Comparator comparator) { this(n); - if (comparator == null) throw new IllegalArgumentException("Comparator cannot be null"); - this.comparator = comparator; + this.comparator = Objects.requireNonNull(comparator); } /** @@ -100,8 +100,9 @@ public List> getGraph() { * 'end' are not connected then an empty array is returned. */ public List reconstructPath(int start, int end) { - if (end < 0 || end >= n) throw new IllegalArgumentException("Invalid node index"); - if (start < 0 || start >= n) throw new IllegalArgumentException("Invalid node index"); + if (end < 0 || end >= n) throw new IndexOutOfBoundsException("Invalid node index: " + end); + if (start < 0 || start >= n) + throw new IndexOutOfBoundsException("Invalid node index: " + start); double dist = dijkstra(start, end); List path = new ArrayList<>(); if (dist == Double.POSITIVE_INFINITY) return path; diff --git a/src/main/java/com/williamfiset/algorithms/graphtheory/DijkstrasShortestPathAdjacencyListWithDHeap.java b/src/main/java/com/williamfiset/algorithms/graphtheory/DijkstrasShortestPathAdjacencyListWithDHeap.java index 0536c4e26..b8f162a94 100644 --- a/src/main/java/com/williamfiset/algorithms/graphtheory/DijkstrasShortestPathAdjacencyListWithDHeap.java +++ b/src/main/java/com/williamfiset/algorithms/graphtheory/DijkstrasShortestPathAdjacencyListWithDHeap.java @@ -15,6 +15,7 @@ import java.util.Collections; import java.util.List; import java.util.NoSuchElementException; +import java.util.Objects; public class DijkstrasShortestPathAdjacencyListWithDHeap { @@ -138,8 +139,9 @@ public double dijkstra(int start, int end) { * 'end' are not connected then an empty array is returned. */ public List reconstructPath(int start, int end) { - if (end < 0 || end >= n) throw new IllegalArgumentException("Invalid node index"); - if (start < 0 || start >= n) throw new IllegalArgumentException("Invalid node index"); + if (end < 0 || end >= n) throw new IndexOutOfBoundsException("Invalid node index: " + end); + if (start < 0 || start >= n) + throw new IndexOutOfBoundsException("Invalid node index: " + start); List path = new ArrayList<>(); double dist = dijkstra(start, end); if (dist == Double.POSITIVE_INFINITY) return path; @@ -233,7 +235,7 @@ public T pollMinValue() { public void insert(int ki, T value) { if (contains(ki)) throw new IllegalArgumentException("index already exists; received: " + ki); - valueNotNullOrThrow(value); + Objects.requireNonNull(value); pm[ki] = sz; im[sz] = ki; values[ki] = value; @@ -347,20 +349,15 @@ private void isNotEmptyOrThrow() { private void keyExistsAndValueNotNullOrThrow(int ki, Object value) { keyExistsOrThrow(ki); - valueNotNullOrThrow(value); + Objects.requireNonNull(value); } private void keyExistsOrThrow(int ki) { if (!contains(ki)) throw new NoSuchElementException("Index does not exist; received: " + ki); } - private void valueNotNullOrThrow(Object value) { - if (value == null) throw new IllegalArgumentException("value cannot be null"); - } - private void keyInBoundsOrThrow(int ki) { - if (ki < 0 || ki >= N) - throw new IllegalArgumentException("Key index out of bounds; received: " + ki); + if (ki < 0 || ki >= N) throw new IndexOutOfBoundsException(ki); } } } diff --git a/src/main/java/com/williamfiset/algorithms/graphtheory/EagerPrimsAdjacencyList.java b/src/main/java/com/williamfiset/algorithms/graphtheory/EagerPrimsAdjacencyList.java index 095486e6e..8b6815001 100644 --- a/src/main/java/com/williamfiset/algorithms/graphtheory/EagerPrimsAdjacencyList.java +++ b/src/main/java/com/williamfiset/algorithms/graphtheory/EagerPrimsAdjacencyList.java @@ -44,9 +44,8 @@ public int compareTo(Edge other) { private Edge[] mstEdges; public EagerPrimsAdjacencyList(List> graph) { - if (graph == null || graph.isEmpty()) throw new IllegalArgumentException(); + this.graph = Objects.requireNonNull(graph); this.n = graph.size(); - this.graph = graph; } // Returns the edges used in finding the minimum spanning tree, @@ -470,7 +469,7 @@ public T pollMinValue() { public void insert(int ki, T value) { if (contains(ki)) throw new IllegalArgumentException("index already exists; received: " + ki); - valueNotNullOrThrow(value); + Objects.requireNonNull(value); pm[ki] = sz; im[sz] = ki; values[ki] = value; @@ -584,20 +583,15 @@ private void isNotEmptyOrThrow() { private void keyExistsAndValueNotNullOrThrow(int ki, Object value) { keyExistsOrThrow(ki); - valueNotNullOrThrow(value); + Objects.requireNonNull(value); } private void keyExistsOrThrow(int ki) { if (!contains(ki)) throw new NoSuchElementException("Index does not exist; received: " + ki); } - private void valueNotNullOrThrow(Object value) { - if (value == null) throw new IllegalArgumentException("value cannot be null"); - } - private void keyInBoundsOrThrow(int ki) { - if (ki < 0 || ki >= N) - throw new IllegalArgumentException("Key index out of bounds; received: " + ki); + if (ki < 0 || ki >= N) throw new IndexOutOfBoundsException(ki); } /* Test functions */ diff --git a/src/main/java/com/williamfiset/algorithms/graphtheory/EulerianPathDirectedEdgesAdjacencyList.java b/src/main/java/com/williamfiset/algorithms/graphtheory/EulerianPathDirectedEdgesAdjacencyList.java index 12fd97dd8..1023928c4 100644 --- a/src/main/java/com/williamfiset/algorithms/graphtheory/EulerianPathDirectedEdgesAdjacencyList.java +++ b/src/main/java/com/williamfiset/algorithms/graphtheory/EulerianPathDirectedEdgesAdjacencyList.java @@ -17,6 +17,7 @@ import java.util.Arrays; import java.util.LinkedList; import java.util.List; +import java.util.Objects; public class EulerianPathDirectedEdgesAdjacencyList { @@ -27,9 +28,8 @@ public class EulerianPathDirectedEdgesAdjacencyList { private List> graph; public EulerianPathDirectedEdgesAdjacencyList(List> graph) { - if (graph == null) throw new IllegalArgumentException("Graph cannot be null"); + this.graph = Objects.requireNonNull(graph); n = graph.size(); - this.graph = graph; path = new LinkedList<>(); } diff --git a/src/main/java/com/williamfiset/algorithms/graphtheory/Kosaraju.java b/src/main/java/com/williamfiset/algorithms/graphtheory/Kosaraju.java index 33471a126..05b05e302 100644 --- a/src/main/java/com/williamfiset/algorithms/graphtheory/Kosaraju.java +++ b/src/main/java/com/williamfiset/algorithms/graphtheory/Kosaraju.java @@ -29,8 +29,7 @@ public class Kosaraju { private List> transposeGraph; public Kosaraju(List> graph) { - if (graph == null) throw new IllegalArgumentException("Graph cannot be null."); - this.graph = graph; + this.graph = Objects.requireNonNull(graph); n = graph.size(); } diff --git a/src/main/java/com/williamfiset/algorithms/graphtheory/KruskalsEdgeListPartialSortSolver.java b/src/main/java/com/williamfiset/algorithms/graphtheory/KruskalsEdgeListPartialSortSolver.java index b3a651014..722ae1226 100644 --- a/src/main/java/com/williamfiset/algorithms/graphtheory/KruskalsEdgeListPartialSortSolver.java +++ b/src/main/java/com/williamfiset/algorithms/graphtheory/KruskalsEdgeListPartialSortSolver.java @@ -11,6 +11,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.Objects; import java.util.PriorityQueue; public class KruskalsEdgeListPartialSortSolver { @@ -47,8 +48,8 @@ public int compareTo(Edge other) { // edges - A list of undirected edges. // n - The number of nodes in the input graph. public KruskalsEdgeListPartialSortSolver(List edges, int n) { - if (edges == null || n <= 1) throw new IllegalArgumentException(); - this.edges = edges; + this.edges = Objects.requireNonNull(edges); + if (n <= 1) throw new IllegalArgumentException(); this.n = n; } diff --git a/src/main/java/com/williamfiset/algorithms/graphtheory/LazyPrimsAdjacencyList.java b/src/main/java/com/williamfiset/algorithms/graphtheory/LazyPrimsAdjacencyList.java index 53f4e5d5a..389b71bfe 100644 --- a/src/main/java/com/williamfiset/algorithms/graphtheory/LazyPrimsAdjacencyList.java +++ b/src/main/java/com/williamfiset/algorithms/graphtheory/LazyPrimsAdjacencyList.java @@ -42,9 +42,9 @@ public int compareTo(Edge other) { private Edge[] mstEdges; public LazyPrimsAdjacencyList(List> graph) { - if (graph == null || graph.isEmpty()) throw new IllegalArgumentException(); + this.graph = Objects.requireNonNull(graph); + if (graph.isEmpty()) throw new IllegalArgumentException(); this.n = graph.size(); - this.graph = graph; } // Returns the edges used in finding the minimum spanning tree, diff --git a/src/main/java/com/williamfiset/algorithms/graphtheory/TarjanSccSolverAdjacencyList.java b/src/main/java/com/williamfiset/algorithms/graphtheory/TarjanSccSolverAdjacencyList.java index 18f547b43..a1721949c 100644 --- a/src/main/java/com/williamfiset/algorithms/graphtheory/TarjanSccSolverAdjacencyList.java +++ b/src/main/java/com/williamfiset/algorithms/graphtheory/TarjanSccSolverAdjacencyList.java @@ -33,9 +33,8 @@ public class TarjanSccSolverAdjacencyList { private static final int UNVISITED = -1; public TarjanSccSolverAdjacencyList(List> graph) { - if (graph == null) throw new IllegalArgumentException("Graph cannot be null."); + this.graph = Objects.requireNonNull(graph); n = graph.size(); - this.graph = graph; } // Returns the number of strongly connected components in the graph. diff --git a/src/main/java/com/williamfiset/algorithms/graphtheory/TspDynamicProgrammingIterative.java b/src/main/java/com/williamfiset/algorithms/graphtheory/TspDynamicProgrammingIterative.java index a75509b8f..b31b5b77f 100644 --- a/src/main/java/com/williamfiset/algorithms/graphtheory/TspDynamicProgrammingIterative.java +++ b/src/main/java/com/williamfiset/algorithms/graphtheory/TspDynamicProgrammingIterative.java @@ -11,6 +11,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.Objects; public class TspDynamicProgrammingIterative { @@ -25,10 +26,13 @@ public TspDynamicProgrammingIterative(double[][] distance) { } public TspDynamicProgrammingIterative(int start, double[][] distance) { + + Objects.requireNonNull(distance); N = distance.length; if (N <= 2) throw new IllegalStateException("N <= 2 not yet supported."); - if (N != distance[0].length) throw new IllegalStateException("Matrix must be square (n x n)"); + if (N != distance[0].length) + throw new IllegalArgumentException("Matrix must be square (n x n)"); if (start < 0 || start >= N) throw new IllegalArgumentException("Invalid start node."); if (N > 32) throw new IllegalArgumentException( diff --git a/src/main/java/com/williamfiset/algorithms/graphtheory/TspDynamicProgrammingRecursive.java b/src/main/java/com/williamfiset/algorithms/graphtheory/TspDynamicProgrammingRecursive.java index 9513b2262..0db5d15ed 100644 --- a/src/main/java/com/williamfiset/algorithms/graphtheory/TspDynamicProgrammingRecursive.java +++ b/src/main/java/com/williamfiset/algorithms/graphtheory/TspDynamicProgrammingRecursive.java @@ -33,7 +33,7 @@ public TspDynamicProgrammingRecursive(double[][] distance) { public TspDynamicProgrammingRecursive(int startNode, double[][] distance) { - this.distance = distance; + this.distance = Objects.requireNonNull(distance); N = distance.length; START_NODE = startNode; diff --git a/src/main/java/com/williamfiset/algorithms/graphtheory/analysis/PrimsGraphRepresentationAnaylsis.java b/src/main/java/com/williamfiset/algorithms/graphtheory/analysis/PrimsGraphRepresentationAnaylsis.java index e4dd9ce80..d6e961e3c 100644 --- a/src/main/java/com/williamfiset/algorithms/graphtheory/analysis/PrimsGraphRepresentationAnaylsis.java +++ b/src/main/java/com/williamfiset/algorithms/graphtheory/analysis/PrimsGraphRepresentationAnaylsis.java @@ -134,9 +134,9 @@ private static class PrimsAdjList { private Edge[] mstEdges; public PrimsAdjList(List> graph) { - if (graph == null || graph.isEmpty()) throw new IllegalArgumentException(); + this.graph = Objects.requireNonNull(graph); + if (graph.isEmpty()) throw new IllegalArgumentException(); this.n = graph.size(); - this.graph = graph; } // Returns the edges used in finding the minimum spanning tree, @@ -241,10 +241,10 @@ private static class PrimsAdjMatrix { private Edge[] mstEdges; public PrimsAdjMatrix(Integer[][] graph) { - if (graph == null || graph.length == 0 || graph[0].length != graph.length) + this.graph = Objects.requireNonNull(graph); + if (graph.length == 0 || graph[0].length != graph.length) throw new IllegalArgumentException(); this.n = graph.length; - this.graph = graph; } // Returns the edges used in finding the minimum spanning tree, @@ -473,7 +473,7 @@ public T pollMinValue() { public void insert(int ki, T value) { if (contains(ki)) throw new IllegalArgumentException("index already exists; received: " + ki); - valueNotNullOrThrow(value); + Objects.requireNonNull(value); pm[ki] = sz; im[sz] = ki; values[ki] = value; @@ -587,20 +587,15 @@ private void isNotEmptyOrThrow() { private void keyExistsAndValueNotNullOrThrow(int ki, Object value) { keyExistsOrThrow(ki); - valueNotNullOrThrow(value); + Objects.requireNonNull(value); } private void keyExistsOrThrow(int ki) { if (!contains(ki)) throw new NoSuchElementException("Index does not exist; received: " + ki); } - private void valueNotNullOrThrow(Object value) { - if (value == null) throw new IllegalArgumentException("value cannot be null"); - } - private void keyInBoundsOrThrow(int ki) { - if (ki < 0 || ki >= N) - throw new IllegalArgumentException("Key index out of bounds; received: " + ki); + if (ki < 0 || ki >= N) throw new IndexOutOfBoundsException(ki); } /* Test functions */ diff --git a/src/main/java/com/williamfiset/algorithms/graphtheory/examples/EagerPrimsExample.java b/src/main/java/com/williamfiset/algorithms/graphtheory/examples/EagerPrimsExample.java index 835070f2c..e38e0b533 100644 --- a/src/main/java/com/williamfiset/algorithms/graphtheory/examples/EagerPrimsExample.java +++ b/src/main/java/com/williamfiset/algorithms/graphtheory/examples/EagerPrimsExample.java @@ -116,9 +116,9 @@ private static class MinimumSpanningTreeSolver { private Edge[] mstEdges; public MinimumSpanningTreeSolver(List> graph) { - if (graph == null || graph.isEmpty()) throw new IllegalArgumentException(); + this.graph = Objects.requireNonNull(graph); + if (graph.isEmpty()) throw new IllegalArgumentException(); this.n = graph.size(); - this.graph = graph; } // Returns the edges used in finding the minimum spanning tree, @@ -280,7 +280,7 @@ public T pollMinValue() { public void insert(int ki, T value) { if (contains(ki)) throw new IllegalArgumentException("index already exists; received: " + ki); - valueNotNullOrThrow(value); + Objects.requireNonNull(value); pm[ki] = sz; im[sz] = ki; values[ki] = value; @@ -394,20 +394,15 @@ private void isNotEmptyOrThrow() { private void keyExistsAndValueNotNullOrThrow(int ki, Object value) { keyExistsOrThrow(ki); - valueNotNullOrThrow(value); + Objects.requireNonNull(value); } private void keyExistsOrThrow(int ki) { if (!contains(ki)) throw new NoSuchElementException("Index does not exist; received: " + ki); } - private void valueNotNullOrThrow(Object value) { - if (value == null) throw new IllegalArgumentException("value cannot be null"); - } - private void keyInBoundsOrThrow(int ki) { - if (ki < 0 || ki >= N) - throw new IllegalArgumentException("Key index out of bounds; received: " + ki); + if (ki < 0 || ki >= N) throw new IndexOutOfBoundsException(ki); } /* Test functions */ diff --git a/src/main/java/com/williamfiset/algorithms/graphtheory/networkflow/BipartiteGraphCheckAdjacencyList.java b/src/main/java/com/williamfiset/algorithms/graphtheory/networkflow/BipartiteGraphCheckAdjacencyList.java index 72da81a0c..17b187a92 100644 --- a/src/main/java/com/williamfiset/algorithms/graphtheory/networkflow/BipartiteGraphCheckAdjacencyList.java +++ b/src/main/java/com/williamfiset/algorithms/graphtheory/networkflow/BipartiteGraphCheckAdjacencyList.java @@ -10,6 +10,7 @@ import com.williamfiset.algorithms.utils.graphutils.Utils; import java.util.List; +import java.util.Objects; public class BipartiteGraphCheckAdjacencyList { @@ -22,9 +23,8 @@ public class BipartiteGraphCheckAdjacencyList { public static final int RED = 0b10, BLACK = (RED ^ 1); public BipartiteGraphCheckAdjacencyList(List> graph) { - if (graph == null) throw new IllegalArgumentException("Graph cannot be null."); + this.graph = Objects.requireNonNull(graph); n = graph.size(); - this.graph = graph; } // Checks whether the input graph is bipartite. diff --git a/src/main/java/com/williamfiset/algorithms/other/SlidingWindowMaximum.java b/src/main/java/com/williamfiset/algorithms/other/SlidingWindowMaximum.java index 0534cb6cd..e79ab9673 100644 --- a/src/main/java/com/williamfiset/algorithms/other/SlidingWindowMaximum.java +++ b/src/main/java/com/williamfiset/algorithms/other/SlidingWindowMaximum.java @@ -10,6 +10,7 @@ import java.util.ArrayDeque; import java.util.Deque; +import java.util.Objects; public class SlidingWindowMaximum { @@ -19,8 +20,7 @@ public class SlidingWindowMaximum { Deque deque = new ArrayDeque<>(); public SlidingWindowMaximum(int[] values) { - if (values == null) throw new IllegalArgumentException(); - this.values = values; + this.values = Objects.requireNonNull(values); N = values.length; } diff --git a/src/main/java/com/williamfiset/algorithms/strings/LongestCommonSubstring.java b/src/main/java/com/williamfiset/algorithms/strings/LongestCommonSubstring.java index f0718493b..bd476f37d 100644 --- a/src/main/java/com/williamfiset/algorithms/strings/LongestCommonSubstring.java +++ b/src/main/java/com/williamfiset/algorithms/strings/LongestCommonSubstring.java @@ -64,8 +64,7 @@ public abstract static class SuffixArray { private boolean constructedLcpArray = false; public SuffixArray(int[] text) { - if (text == null) throw new IllegalArgumentException("Text cannot be null."); - this.T = text; + this.T = Objects.requireNonNull(text); this.N = text.length; } @@ -315,7 +314,7 @@ public static class LcsSolver { // TODO(williamfiset): support LCS with strings as int arrays for larger alphabet sizes. public LcsSolver(String[] strings) { - if (strings == null || strings.length <= 1) + if (Objects.requireNonNull(strings).length <= 1) throw new IllegalArgumentException("Invalid strings array provided."); this.strings = strings; } @@ -503,8 +502,7 @@ static class SlidingWindowMinimum { Deque deque = new ArrayDeque<>(); public SlidingWindowMinimum(int[] values) { - if (values == null) throw new IllegalArgumentException(); - this.values = values; + this.values = Objects.requireNonNull(values); N = values.length; } diff --git a/src/main/java/com/williamfiset/algorithms/utils/graphutils/Utils.java b/src/main/java/com/williamfiset/algorithms/utils/graphutils/Utils.java index 6fcf3f5e5..27d5a4d40 100644 --- a/src/main/java/com/williamfiset/algorithms/utils/graphutils/Utils.java +++ b/src/main/java/com/williamfiset/algorithms/utils/graphutils/Utils.java @@ -7,6 +7,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.Objects; public final class Utils { @@ -24,12 +25,12 @@ public static List> createEmptyAdjacencyList(int n) { /** Adds an unweighted directed edge from the node at index 'from' to the node at index 'to'. */ public static void addDirectedEdge(List> graph, int from, int to) { - if (graph == null) throw new IllegalArgumentException("graph cannot be null"); + Objects.requireNonNull(graph); int n = graph.size(); if (from < 0 || from >= n) - throw new IllegalArgumentException("'from' node index out of bounds; received: " + from); + throw new IndexOutOfBoundsException("'from' node index out of bounds; received: " + from); if (to < 0 || to >= n) - throw new IllegalArgumentException("'to' node index out of bounds; received: " + to); + throw new IndexOutOfBoundsException("'to' node index out of bounds; received: " + to); graph.get(from).add(to); } diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/balancedtree/RedBlackTreeTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/balancedtree/RedBlackTreeTest.java index dd4e536cf..eb3b543ad 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/balancedtree/RedBlackTreeTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/balancedtree/RedBlackTreeTest.java @@ -22,7 +22,7 @@ public void setup() { @Test public void testNullInsertion() { - assertThrows(IllegalArgumentException.class, () -> tree.insert(null)); + assertThrows(NullPointerException.class, () -> tree.insert(null)); } @Test diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/balancedtree/TreapTreeTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/balancedtree/TreapTreeTest.java index 51f469e8b..fed23c76d 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/balancedtree/TreapTreeTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/balancedtree/TreapTreeTest.java @@ -25,7 +25,7 @@ public void setup() { @Test public void testNullInsertion() { - assertThrows(IllegalArgumentException.class, () -> tree.insert(null)); + assertThrows(NullPointerException.class, () -> tree.insert(null)); } @Test diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/fenwicktree/FenwickTreeRangeQueryPointUpdateTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/fenwicktree/FenwickTreeRangeQueryPointUpdateTest.java index 30cf0caef..bf7841630 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/fenwicktree/FenwickTreeRangeQueryPointUpdateTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/fenwicktree/FenwickTreeRangeQueryPointUpdateTest.java @@ -171,7 +171,7 @@ public static long randValue() { @Test public void testIllegalCreation() { - assertThrows(IllegalArgumentException.class, () -> new FenwickTreeRangeQueryPointUpdate(null)); + assertThrows(NullPointerException.class, () -> new FenwickTreeRangeQueryPointUpdate(null)); } // Generate a list of random numbers, one based diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/fenwicktree/FenwickTreeRangeUpdatePointQueryTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/fenwicktree/FenwickTreeRangeUpdatePointQueryTest.java index 13e34e35f..d9a84a5d8 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/fenwicktree/FenwickTreeRangeUpdatePointQueryTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/fenwicktree/FenwickTreeRangeUpdatePointQueryTest.java @@ -38,7 +38,7 @@ public void setup() { @Test public void testIllegalCreation() { - assertThrows(IllegalArgumentException.class, () -> new FenwickTreeRangeUpdatePointQuery(null)); + assertThrows(NullPointerException.class, () -> new FenwickTreeRangeUpdatePointQuery(null)); } @Test diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableLinearProbingTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableLinearProbingTest.java index 07ed449c7..5c05083da 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableLinearProbingTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableLinearProbingTest.java @@ -48,7 +48,7 @@ public void setup() { @Test public void testNullKey() { - assertThrows(IllegalArgumentException.class, () -> map.put(null, 5)); + assertThrows(NullPointerException.class, () -> map.put(null, 5)); } @Test diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableQuadraticProbingTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableQuadraticProbingTest.java index fffc00538..26a2a2b53 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableQuadraticProbingTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/hashtable/HashTableQuadraticProbingTest.java @@ -48,7 +48,7 @@ public void setup() { @Test public void testNullKey() { - assertThrows(IllegalArgumentException.class, () -> map.put(null, 5)); + assertThrows(NullPointerException.class, () -> map.put(null, 5)); } @Test diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/kdtree/GeneralKDTreeTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/kdtree/GeneralKDTreeTest.java index 4d2005331..de3af9d29 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/kdtree/GeneralKDTreeTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/kdtree/GeneralKDTreeTest.java @@ -36,7 +36,7 @@ public void testInsert() { @Test public void testInsertNull() { GeneralKDTree kdTree = new GeneralKDTree(2); - assertThrows(IllegalArgumentException.class, () -> kdTree.insert(null)); + assertThrows(NullPointerException.class, () -> kdTree.insert(null)); } @Test @@ -68,7 +68,7 @@ public void testSearch() { @Test public void testSearchNull() { GeneralKDTree kdTree = new GeneralKDTree(2); - assertThrows(IllegalArgumentException.class, () -> kdTree.search(null)); + assertThrows(NullPointerException.class, () -> kdTree.search(null)); } @Test @@ -176,7 +176,7 @@ public void testDelete() { @Test public void testDeleteNull() { GeneralKDTree kdTree = new GeneralKDTree(2); - assertThrows(IllegalArgumentException.class, () -> kdTree.delete(null)); + assertThrows(NullPointerException.class, () -> kdTree.delete(null)); } @Test diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/SegmentTreeWithPointersTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/SegmentTreeWithPointersTest.java index 9d9f8374c..3688dea32 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/SegmentTreeWithPointersTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/segmenttree/SegmentTreeWithPointersTest.java @@ -16,7 +16,7 @@ public void setup() {} @Test public void testIllegalSegmentTreeCreation1() { assertThrows( - IllegalArgumentException.class, + NullPointerException.class, () -> { Node tree = new Node(null); }); diff --git a/src/test/java/com/williamfiset/algorithms/datastructures/trie/TrieTest.java b/src/test/java/com/williamfiset/algorithms/datastructures/trie/TrieTest.java index b44e4b00c..6eeeabfe8 100644 --- a/src/test/java/com/williamfiset/algorithms/datastructures/trie/TrieTest.java +++ b/src/test/java/com/williamfiset/algorithms/datastructures/trie/TrieTest.java @@ -45,7 +45,7 @@ public void testBadTrieDelete3() { @Test public void testBadTrieInsert() { assertThrows( - IllegalArgumentException.class, + NullPointerException.class, () -> { (new Trie()).insert(null); }); @@ -54,7 +54,7 @@ public void testBadTrieInsert() { @Test public void testBadTrieCount() { assertThrows( - IllegalArgumentException.class, + NullPointerException.class, () -> { (new Trie()).count(null); }); @@ -63,7 +63,7 @@ public void testBadTrieCount() { @Test public void testBadTrieContains() { assertThrows( - IllegalArgumentException.class, + NullPointerException.class, () -> { (new Trie()).contains(null); }); diff --git a/src/test/java/com/williamfiset/algorithms/graphtheory/BreadthFirstSearchAdjacencyListIterativeTest.java b/src/test/java/com/williamfiset/algorithms/graphtheory/BreadthFirstSearchAdjacencyListIterativeTest.java index 917ef9b92..7d6b69e77 100644 --- a/src/test/java/com/williamfiset/algorithms/graphtheory/BreadthFirstSearchAdjacencyListIterativeTest.java +++ b/src/test/java/com/williamfiset/algorithms/graphtheory/BreadthFirstSearchAdjacencyListIterativeTest.java @@ -25,7 +25,7 @@ public void setup() { @Test public void testNullGraphInput() { assertThrows( - IllegalArgumentException.class, () -> new BreadthFirstSearchAdjacencyListIterative(null)); + NullPointerException.class, () -> new BreadthFirstSearchAdjacencyListIterative(null)); } @Test diff --git a/src/test/java/com/williamfiset/algorithms/graphtheory/KosarajuTest.java b/src/test/java/com/williamfiset/algorithms/graphtheory/KosarajuTest.java index 3ce6974c7..a8e19a865 100644 --- a/src/test/java/com/williamfiset/algorithms/graphtheory/KosarajuTest.java +++ b/src/test/java/com/williamfiset/algorithms/graphtheory/KosarajuTest.java @@ -28,7 +28,7 @@ public static void addEdge(List> graph, int from, int to) { @Test public void nullGraphConstructor() { - assertThrowsExactly(IllegalArgumentException.class, () -> new Kosaraju(null)); + assertThrowsExactly(NullPointerException.class, () -> new Kosaraju(null)); } @Test diff --git a/src/test/java/com/williamfiset/algorithms/graphtheory/TarjanSccSolverAdjacencyListTest.java b/src/test/java/com/williamfiset/algorithms/graphtheory/TarjanSccSolverAdjacencyListTest.java index cab07eebf..c5edf7e36 100644 --- a/src/test/java/com/williamfiset/algorithms/graphtheory/TarjanSccSolverAdjacencyListTest.java +++ b/src/test/java/com/williamfiset/algorithms/graphtheory/TarjanSccSolverAdjacencyListTest.java @@ -23,7 +23,7 @@ public static void addEdge(List> graph, int from, int to) { @Test public void nullGraphConstructor() { - assertThrows(IllegalArgumentException.class, () -> new TarjanSccSolverAdjacencyList(null)); + assertThrows(NullPointerException.class, () -> new TarjanSccSolverAdjacencyList(null)); } @Test