• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 140
  • Last Modified:

Generics and Autoboxing

1. For generics, does it mean we define the <Type> during declaration so it makes our life easier?
i.e List<String> ls = new ArrayList<String>;

so the above, the list can only contain String objects and no other types?
this <type> can only be used on collections and arrays?

1a. What is the use of Collection<object> and Collection<?>

2. I'm having issues understanding Autoboxing. I read http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html, still aint sure what its doing and what its for? Is it trying to say Autoboxing is automatic now.. and it is no problem if we do:

int x = 5;
Integer y = x;
int z = y;
0
jedistar
Asked:
jedistar
  • 2
1 Solution
 
CEHJCommented:
>>1. For generics, does it mean we define the <Type> during declaration so it makes our life easier?

Not just to make life easier - it provides compile time type checking

>>so the above, the list can only contain String objects and no other types?

Yes

>>still aint sure what its doing and what its for?

It's to save you have to cast and call intValue() and the like

>>Is it trying to say Autoboxing is automatic now.. and it is no problem if we do:

It's automatic
0
 
CEHJCommented:
>>have to cast

should read

having to call new Integer(n)
0
 
objectsCommented:
1. Allows molre errors to be picked up at compile time, rather than at runtime
Also saves you lots of casting because the compiler knows what type is in collection

1a. Have a read of the following for a good explanation of generics

http://mindprod.com/jgloss/generics.html

2. without it you'd need:

int x = 5;
Integer y = new Integer(x);
int z = y.intValue();
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now