Question

I got a doubt and want to know which class method might have been used by JRE for removing objects in below code. Because remove is having two signatures remove(int) and remove(Object). As a part of AutoBoxing feature, here int will be considered as Integer while adding it to Collection. In this scenario which remove method will receive higher precedence and why? Please share the reasons....

    Vector v=new Vector();
    for(int i=0;i<10;i++)
    {
        v.add(i);           
    }       
    v.remove(5); 
    System.err.println(v);

Regards Sudhakar Chavali

Was it helpful?

Solution

Without constructing an instance of class Integer, the argument is an int and a method of Vector can handle it directly without autoboxing. The compiler use the easiest way as detailed in Java Language Specification.

This version removes the second Integer (index = 1) because it's explicitly an Integer:

import java.util.Vector;

public class VectorAutoBox {
    public static void main(String[] args) {
        Vector vector = new Vector();
        vector.add(1);
        vector.add(5);
        vector.add(2);
        vector.add(3);
        vector.add(4);
        vector.add(6);
        System.out.println(vector);
        vector.remove( new Integer( 5 )); // case 1
//      vector.remove( 5 );               // case 2
        System.out.println(vector);
    }
}

Outputs for case 1:

[1, 5, 2, 3, 4, 6]
[1, 2, 3, 4, 6]      value '5' at index 1 removed

Outputs for case 2:

[1, 5, 2, 3, 4, 6]
[1, 5, 2, 3, 4]      value '6' at index 5 removed

OTHER TIPS

It picks up index one

package com.jigar.stackoverflow.question.java;

public class VectorAutoBox {
    public static void main(String[] args) {
        Vector vector = new Vector();
        vector.add(1);
        vector.add(5);
        vector.add(2);
        vector.add(3);
        vector.add(4);
        vector.add(6);
        System.out.println(vector);
        vector.remove(5);
        System.out.println(vector);
    }
}

Output

[1, 5, 2, 3, 4, 6]
[1, 5, 2, 3, 4]

The rules to determine what methods are applicable are detailed in the JLS #15.12.2. In substance, methods that do no require boxing/unboxing have priority over methods that would require a boxing/unboxing operation:

  • The first phase (§15.12.2.2) performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the second phase.
  • The second phase (§15.12.2.3) performs overload resolution while allowing boxing and unboxing, but still precludes the use of variable arity method invocation.

So remove(int) is called when you write remove(5);.

Note that Vector is obsolete for most purposes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top