Bael 4215 creating generic array (#10178)

* Initial commit for generic arrays, using T[] and Object[]

* Add CollectionsList

* Create generic arrays example with a Stack

* Remove custom exception classes + throw RuntimeException instead.
This commit is contained in:
developerDiv 2020-11-16 18:08:49 +00:00 committed by GitHub
parent c6f8c56572
commit 43fad6ba95
3 changed files with 98 additions and 0 deletions

View File

@ -0,0 +1,30 @@
package com.baeldung.genericarrays;
import java.lang.reflect.Array;
public class MyStack<E> {
private E[] elements;
private int size = 0;
public MyStack(Class<E> clazz, int capacity) {
elements = (E[]) Array.newInstance(clazz, capacity);
}
public void push(E item) {
if (size == elements.length) {
throw new RuntimeException();
}
elements[size++] = item;
}
public E pop() {
if (size == 0) {
throw new RuntimeException();
}
return elements[--size];
}
public E[] getAllElements() {
return elements;
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.genericarrays;
import org.junit.Test;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class ListToArrayUnitTest {
@Test
public void givenListOfItems_whenToArray_thenReturnArrayOfItems() {
List<String> items = new LinkedList<>();
items.add("first item");
items.add("second item");
String[] itemsAsArray = items.toArray(new String[0]);
assertEquals("first item", itemsAsArray[0]);
assertEquals("second item", itemsAsArray[1]);
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.genericarrays;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class MyStackUnitTest {
@Test
public void givenStackWithTwoItems_whenPop_thenReturnLastAdded() {
MyStack<String> myStack = new MyStack<>(String.class, 2);
myStack.push("hello");
myStack.push("example");
assertEquals("example", myStack.pop());
}
@Test (expected = RuntimeException.class)
public void givenStackWithFixedCapacity_whenExceedCapacity_thenThrowException() {
MyStack<Integer> myStack = new MyStack<>(Integer.class, 2);
myStack.push(100);
myStack.push(200);
myStack.push(300);
}
@Test(expected = RuntimeException.class)
public void givenStack_whenPopOnEmptyStack_thenThrowException() {
MyStack<Integer> myStack = new MyStack<>(Integer.class, 1);
myStack.push(100);
myStack.pop();
myStack.pop();
}
@Test
public void givenStackWithItems_whenGetAllElements_thenSizeShouldEqualTotal() {
MyStack<String> myStack = new MyStack<>(String.class, 2);
myStack.push("hello");
myStack.push("example");
String[] items = myStack.getAllElements();
assertEquals(2, items.length);
}
}