So I'm working in Java and I want to declare a generic List.
So what I'm doing so far is List<T> list = new ArrayList<T>();
But now I want to add in an element. How do I do that? What does a generic element look like?
I've tried doing something like List.add("x") to see if I can add a string but that doesn't work.
(The reason I'm not declaring a List<String>
is because I have to pass this List into another function that only takes List<T>
as an argument.
< T > is a conventional letter that stands for "Type", and it refers to the concept of Generics in Java. You can use any letter, but you'll see that 'T' is widely preferred. WHAT DOES GENERIC MEAN? Generic is a way to parameterize a class, method, or interface.
You can get and insert the elements of a generic List like this: List<String> list = new ArrayList<String>; String string1 = "a string"; list. add(string1); String string2 = list. get(0);
To update the Box class to use generics, you create a generic type declaration by changing the code "public class Box" to "public class Box<T>". This introduces the type variable, T, that can be used anywhere inside the class. As you can see, all occurrences of Object are replaced by T.
You should either have a generic class or a generic method like below:
public class Test<T> {
List<T> list = new ArrayList<T>();
public Test(){
}
public void populate(T t){
list.add(t);
}
public static void main(String[] args) {
new Test<String>().populate("abc");
}
}
The T is the type of the objects that your list will contain.
You can write List<String>
and use it in a function which needs List<T>
, it shouldn't be a problem since the T is used to say that it can be anything.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With