Here is a piece of code:
@FunctionalInterface
interface NumericFunc<T>{
int fact(T[] a,T b);
}
class MyStringOps{
static <T> int counter(T[] a,T b){
int count=0;
for(int i=0;i<a.length;i++)
if (a[i]==b)
count++;
return count;
}
}
public class Numeric {
static<T> void stringOp(NumericFunc<T> ref,T[] a,T b){
System.out.println(ref.fact(a,b));
}
public static void main(String[] args) {
Integer ing[]={1,2,3,4,5,4,4,4,8};
String str[]={"one","two","three","two","four"};
stringOp(MyStringOps::<Integer>counter,ing,new Integer(4));
stringOp(MyStringOps::<String>counter,str,new String("two"));
}
}
Output for the following code is: 0 0
Here is the same code with a bit of difference:
@FunctionalInterface
interface NumericFunc<T>{
int fact(T[] a,T b);
}
class MyStringOps{
static <T> int counter(T[] a,T b){
int count=0;
for(int i=0;i<a.length;i++)
if (a[i]==b)
count++;
return count;
}
}
public class Numeric {
static<T> void stringOp(NumericFunc<T> ref,T[] a,T b){
System.out.println(ref.fact(a,b));
}
public static void main(String[] args) {
Integer ing[]={1,2,3,4,5,4,4,4,8};
String str[]={"one","two","three","two","four"};
//Deviation from the previous code.Instead of Wrapper classes
//primitive type are used for argument to b.
stringOp(MyStringOps::<Integer>counter,ing,4);
stringOp(MyStringOps::<String>counter,str,"two");
}
}
Output: 4 2
My question is that when we pass new Integer(4) as an argument, when NumericFunc is executed with implementation of counter or in lucid terms when counter is executed shouldn't new Integer(4) be unboxed to 4 and compared with the array and output for the both the code pieces should remain same.
if(new Integer(4)==4)
System.out.println(true);
For this piece Output is true. But if there is an array of type Integer which contains elements of primitive type i.e. int in this case(which according to me should be auto boxed to Integer type and then should be stored in array) and then if you compare it with a Wrapper type it returns false. For e.g. in the above code there is an array ing[] which contains 4 at 3rd index.
if(ing[3]==new Integer(4))
System.out.println(true);
else
System.out.println(false);
Output: false
In this case auto boxing or unboxing doesn't takes place.
Can anyone answer why this happens?