Search code examples
javaoopgeneric-programming

Generic class for list elements


I am practicing programming with generic classes. I want to implement a class for a list element that holds a reference on an object of generic type and a reference on the next list element.

So I came up with this class:

class List<T>{
    T val;
    List next:
}

How would you define the constructor for this class? Any other advice to understand generic classes and their use?


Solution

  • you can leave it with default constructor and then use it List<String> list = new List<String>(); - now val in your class will be String. Another way:

    public class List<T>{
        T val;
        List<T> next;
    
        public List(T val, List<T> next) {
            this.val = val;
            this.next = next;
        };
    
        public T getVal() {
            return val;
        }
    }
    

    And then you can use it this way:

    List<String> strList = new List<String>("test", null);
    System.out.println( strList.getVal() );
    

    as result "test" should be printed

    As for advice, I think the best thing is to read this book: Java Generics and Collections it contains good description and a lot of examples how to use it.