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.

Example:

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){
wrappedList.add(o);
}

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

@Override
public String toString() {
return wrappedList.toString();
}

public static void main(String[] args) {

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

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

}

}

No comments:

Post a Comment

Creating REST APIs with OpenAPI, Spring Boot 3.3.3, Java 21, and Jakarta

 Introduction In today's software landscape, designing robust and scalable REST APIs is a crucial aspect of application development. Wit...