[PJUG Javamail] Another puzzel, stumpled across this one while I was coding
Christian Pich
cmpich at cs.uoregon.edu
Mon Oct 9 10:06:31 EDT 2006
Brian, that is a good one.
What the two methods do are: Add the numbers 1 to 4 into an array list
and then
remove one element and that call is what is different in your two methods.
In your first method you call the remove()-method with an integer, a
method that interprets the integer number as the index of the element
you want to remove.
In your case it is'1' that means that second element,Integer(2), is
removed. No surprise the output is "134"
In your second method you call the remove()-method with a long type
variable, however there is no
method in the ArrayList class with that signature. Unfortunately in your
case, there is a method that takes an Object
as a single argument and that is the one that is called! Your long-typed
variable is turned into a Long
object via auto-boxing. In this case you remove the object Long(1) which
is the first element!
Your output creates: "234". No Surprise!?
If you call the remove-method with
remove((long) 1)
the argument is turned into a Long object again but now the object is
not identical to the one
you added in your loop before and the output is
"1234"
i.e. no element is removed.
Conclusion: long and integer types are different! Java 5 auto-boxing turns
primitive type variables into object-types if it sees a need to do this.
As this is
done silently this new feature is a source for a new type of bug...
Thanks for sharing this example.
Christian
Brian Mason wrote:
> WARNING,
> This is for fun. If you dont understand the statement, "This is for
> fun", then please skip the email.
>
> What is the output from each of the two functions below????
> a) 134
> b) 234
>
> Are they same, are they different??
>
> Have fun.
>
> static public void stuff1(){
> ArrayList<Integer> stuff=new ArrayList<Integer>();
> int firstOne=1;
> for (int i = firstOne; i < 5; i++) {
> stuff.add(i);
> }
>
> stuff.remove(firstOne);
> for (Integer elem : stuff) {
> System.out.print(elem);
> }
> System.out.println("");
> }
> static public void stuff2(){
> ArrayList<Long> stuff=new ArrayList<Long>();
> long firstOne=1;
> for (long i = firstOne; i < 5; i++) {
> stuff.add(i);
> }
>
> stuff.remove(firstOne);
> for (long elem : stuff) {
> System.out.print(elem);
> }
> System.out.println("");
> }
>
> _______________________________________________
> Web Site - http://www.pjug.org/
> Javamail mailing list
> Javamail at pjug.org
> http://www.pjug.org/mailman/listinfo/javamail_pjug.org
>
--
------------------------------------------------------------------------
Christian Pich, Ph.D.
University of Oregon
Zebrafish Information Network
Email: cmpich at cs.uoregon.edu
Web: http://www.zfin.org
------------------------------------------------------------------------
More information about the Javamail
mailing list