Monday, January 2, 2023

Java Generics - List

  • Only instances of that type can be inserted
            List<T> list = new ArrayList<T>();
  • list − object of List interface.
  • T − The generic type parameter passed during list declaration.


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

public class GenericList <T>{

List<T> wrappedList;

public GenericList() {
this.wrappedList = new ArrayList<>();
public GenericList(List<T> wrappedList) {
this.wrappedList = wrappedList;

//get method with custom one
public T myGet(int index){
return wrappedList.get(index);

//add method with custom one
public void myAdd(T o){

//remove method with custom one
public T myRemove(int index){
return wrappedList.remove(index);

public String toString() {
return wrappedList.toString();

public static void main(String[] args) {

GenericList<CharSequence> g = new GenericList<>();
var o = g.myGet(0);
System.out.println("Element 0 = "+o);

System.out.println("Wrapped List "+g.myRemove(0));



No comments:

Post a Comment

Multiple Data Sources in Spring Boot 3 with Java 21

  In this blog post, we'll explore the configuration and setup for a Spring Boot 3 application with Java 21 that uses multiple data sour...