k4h4shi
9/3/2017 - 11:17 AM

Generics of Java

Generics of Java

import java.util.ArrayList;
import java.util.List;

public class NumberStack<E extends Number>{
  private List<E> taskList;
  
  public NumberStack() {
    taskList = new ArrayList<>();
  }
  
  public boolean push(E task) {
    return taskList.add(task);
  }
  
  public E pop() {
    if(taskList.isEmpty()) {
      return null;
    }
    
    return taskList.remove(taskList.size() - 1);
  }
  
  public static void main(String[] args) {
    NumberStack<Integer> intStack = new NumberStack<>();
    
    NumberStack<Long> longStack = new NumberStack<>();
    
    intStack.push(100);
    intStack.push(200);
    
    Integer numElement = intStack.pop();
    
    if (numElement != null) {
      System.out.println(numElement);
    }
    
    longStack.push(100000l);
    longStack.push(100000l);
    
    Long longElement = longStack.pop();
    
    if(longElement != null) {
      System.out.println(longElement);
    }
  }

}
import java.util.ArrayList;
import java.util.List;

public class GenericStackUtil {
  public static <T> GenericStack<T> as(List<T> list) {
    GenericStack<T> stack = new GenericStack<>();
    list.forEach(stack::push);
    return stack;
  }
  
  public static void main(String[] args) {
    List<String> strList = new ArrayList<>();
    strList.add("Java");
    strList.add("Groovy");
    GenericStack<String> gstack = GenericStackUtil.as(strList);
  }
}
import java.util.ArrayList;
import java.util.List;

public class GenericStack<E> {
  private List<E> taskList;
  
  public GenericStack() {
    taskList = new ArrayList<>();
  }
  
  public boolean push(E task) {
    return taskList.add(task);
  }
  
  public E pop() {
    if (taskList.isEmpty()) {
      return null;
    }
    
    return taskList.remove(taskList.size() - 1);
  }
  
  public static void main(String[] args) {
    GenericStack<String> genStack = new GenericStack<>();
    
    genStack.push("Scala");
    genStack.push("Groovy");
    genStack.push("Java");
    
    String genElement = genStack.pop();
    
    if (genElement != null) {
      System.out.println(genElement);
    }
    
    GenericStack<Integer> genStack2 = new GenericStack<>();
    
    genStack2.push(100);
    genStack2.push(200);
    
    Integer genElement2 = genStack2.pop();
    
    if(genElement2 != null) {
     System.out.println(genElement2);
    }
  }
}