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

Spring Authorization Server 1.0 with LDAP - Spring Security 6

  Introduction: Spring Authorization Server is a framework that provides implementations of the OAuth 2.1 and OpenID Connect 1.0 specificat...