I finished learning Generics and I didn’t find it easy. However , I did understand it. Here is what I understood. I want you to correct me where I am wrong and answer a few questions 🙂 .
public class LinkedList<T> {
//class definition
}
public class LinkedList<T extends Object> {
//class definition
}
public class LinkedList<T extends Object & java.lang.Serializable> {
//class definition
}
public class LinkedList<T> implements Iterable<T> {
//class definition
}
Itarator<T> and overloads hasNext(), next() and remove()
Questions
1. Please explain the meaning of this in simple words and with an example, if possible:
public class BinaryTree<T extends Comparable<? super T>> what replaces the ?
2. I want to write the above mentioned LinkedList<> class to a file using the writeObject() method. so I declare it as
public class LinkedList<T extends Object> implements Serializable {
//methods and data members
private class Node implements Serializable { //inner class
T object;
Node next;
}
}
Does the inner class have to implement Serializable as well?
About your four first points:
T(including classes that extendT).Object.Serializable(same asclass LinkedList<T extends Serializable> { ... })T, so yeah, it can be used in enhanced loops.Worth noting, when we say “a list that can only contain objects of the specified type”, we should say “should” instead of “can”. Unless you pass
Class<?>objects around, Java (runtime) will not check the values passed in actually comply, only the compiler will, and only based on the visible static type, which could’ve been manually changed (that’d issue a warning).About the questions:
BinaryTreethat contains objects that areComparableto any object of the same class asTor any of its supertypes (Objectis one supertype of all classes, essentially all classes thatTextends and all interfaces it implements).writeObject, then all non-transient (i.e. that you cannot rebuild based on other data) instance fields of that object need to beSerializableas well, orwriteObjectwill ignore them. Your code extract isn’t quite sufficient to tell whetherNodeneeds to beSerializableor not, but it probably needs to given the general idea of theListexample.