Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

autoboxing and generics

Tags:

java

I am actually confused on the both the topics, can anyone explain me.

ArrayList<Long> queryParms = new ArrayList<Long>();
  1. Is the above one called generics or autoboxing and what is unboxing?
  2. Is it a best practice?
  3. Some say Autoboxing is evil thing.
  4. If i use generics, can i avoid autoboxing and unboxing?
like image 203
John Avatar asked Sep 27 '10 09:09

John


People also ask

What do you mean by Autoboxing?

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.

What is the difference between Autoboxing and boxing?

Boxing is the mechanism (ie, from int to Integer ); autoboxing is the feature of the compiler by which it generates boxing code for you.

Why is Autoboxing used?

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.

What are generics in Java?

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.


1 Answers

  1. 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);
    
  2. 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).

  3. 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.

  4. 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.

like image 146
Vivien Barousse Avatar answered Nov 01 '22 23:11

Vivien Barousse