I am actually confused on the both the topics, can anyone explain me.
ArrayList<Long> queryParms = new ArrayList<Long>();
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.
Boxing is the mechanism (ie, from int to Integer ); autoboxing is the feature of the compiler by which it generates boxing code for you.
Autoboxing and unboxing lets developers write cleaner code, making it easier to read. The technique lets us use primitive types and Wrapper class objects interchangeably and we do not need to perform any typecasting explicitly.
Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.
The above is an example of generics. Auto-boxing would be the automatic conversion, by the compiler, of a primitive type in a wrapper type, and vice versa. In your case, for example, from a long
variable in a Long
variable:
long param = 13L;
queryParms.add(param);
Using generics? Yes. It allows you to specify what your list will contain. You should use them. Using auto-boxing? Yes, it simplifies the code, and you don't have to worry about conversions between primitive variable types into wrapper (and vice-versa).
Auto-boxing isn't evil (IMHO). They are some corner cases in which auto-boxing can be very annoying, but if you know how it works, you shouldn't have to worry about it. Here is the Sun (now Oracle) paper on auto-boxing, if you need to know more about it.
If you want to create a list that contains wrappers (in your case, Long
), you'll have to deal with type conversion. You can use explicit type conversion, or you can use auto-boxing.
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