• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Rob Spoor
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
  • Scott Selikoff
Bartenders:
  • Piet Souris
  • Jj Roberts
  • fred rosenberger

autoboxing in vectors

 
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I have a doubt regarding autoboxing.
When we try to add an primitive to vectors doesn't autoboxing automatically converts the primitive to wrapper class?
like is this not a valid statement:
2) Vector v=new Vector();
v.addElement(99);

What are rules of autoboxing.When it comes into play?
Thanks in advance.
 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Vector take any Object if we don't specify the type like Vector<object_type> . all the primitives that are added will converted to wrapper classes. Check your have compiler if the version has autoboxing?

import java.util.*;
public class D {

class sub {

sub() {
System.out.println("created a sub");
}

public String toString() {
return "Object::sub";
}
}

D() {
Vector v = new Vector();
v.addElement(99);
v.addElement("some string");
v.addElement(new sub());
for (Object i : v) {
System.out.println("Value:: " + i + "\t Class:: " + i.getClass().getName());
}
}

public static void main(String[] args) {
D sub = new D();
}
}

the above code prints

Value:: 99 Class:: java.lang.Integer
Value:: some string Class:: java.lang.String
Value:: Object::sub Class:: D$su
 
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
it applies to all the Collection (concrete) (sub-)classes maps,sets list etc
 
reply
    Bookmark Topic Watch Topic
  • New Topic