Hello. It's Kecho. ** Do you guys use Generics? ** ** I learned for the first time today. I mean, I hadn't seen it before, but I finally came across a place to learn.
I think the one I meet most is the list. I think you have made the following declaration.
List<String> list = new ArrayList<>();
I only knew that it was a variable length array. Classes that use this <> are called generic classes.
List<String> list
First of all, this part. List is an interface that holds and handles multiple elements like an array ** in the first place. Not limited to String, you can store objects of various types. (Only one type.) So, the above declaration stipulates that String will be stored this time.
new ArrayList<>();
Next this part. The <> is empty, but I'm just omitting it. (Type can be inferred from the String on the left side)
Let's touch on generics from a broader perspective, not just the list. The simple definition is as follows.
public class Gene<T> {
private T t;
public void setT(T t) {
this.t = t;
}
public T getT() {
return t;
}
}
The usage is as follows
Gene<String> g1 = new Gene<>(); //Fixed with String type
Gene<Integer> g2 = new Gene<>(); //Fixed as Integer type
g1.setT("test");
System.out.print(g1.getT()); // test
g2.setT(24);
System.out.print(g2.getT()); // 24
In this example, we were able to use multiple classes for the same class.
public class GeneObj {
Object t;
public void setT(Object t) {
this.t = t;
}
public Object getT() {
return t;
}
}
I tried using the Object class for the part that was limited by type T. Let's use it.
GeneObj g1 = new GeneObj();
GeneObj g2 = new GeneObj();
g1.setT("test");
System.out.print(g1.getT()); // test
g2.setT(24);
System.out.print(g2.getT()); // 24
You could write it with similar code.
Do I have to use Generics? ?? ??
Both work in this example, but there is a problem with using Object. Simply put, this class is awkward to use.
GeneObj g1 = new GeneObj(); //Fixed with String type
g1.setT("1");
Integer res = (Integer) g1.getT() + 1; //Occurrence of ClassCastException
System.out.print(res);
Above, I accidentally packed a String instead of an Integer. Therefore, ClassCastException occurred when casting to Integer class. From the user's point of view, they have to know the type that they setT, which is a hotbed of bugs. ** With Generics, you don't have to use a cast in the first place and you can notice it with a compile error. ** **
Generics are needed to balance type flexibility with code maintainability
Recommended Posts