Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why this method can not be overloaded? (SE5)

 
Ling Mike
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class testVararg{

private static void method(int... i){
System.out.println("in method1(int... i)");
}
private static void method(int[] i){
System.out.println("in method(int[] i)");
}

public static void main(String[] args){
int[] a = {12,53,543,24,324,456,24};
method(2,3,4,5,1);
method(a);
}
}
-----------
So, if I want to invoke the method() with the "different arguments"(I think the int array reference variable "a" is different from "2,3,4,5,1".)What can I do?
 
Gowher Naik
Ranch Hand
Posts: 643
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
int... i which u have used in first method is varargs . varargs is actually an single dimensional array.
In 2nd method u are passing an array which is already present in first method.
So there is compile time error.
 
Ling Mike
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.

But if I comment "method(int...i)", the invoking "method(2,3,4,5)" will not be run. And if I comment "method(int[] a)", the invoking "method(a)" will not be run. So how can I solve this?
 
Gowher Naik
Ranch Hand
Posts: 643
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ur first method will satisfy both method calls (method(2,3,4,5,1) method(a)),so comment 2nd method only.
 
GANESHKUMAR Parthsarathi
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

U can get the ans. from this link

Click this Link


The last para gives the ans.

Regards,
Ganeshkumar.
 
GANESHKUMAR Parthsarathi
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My Guess is var arg also considered as an array type. That's why we are not able to overload with an array type of same int.

But if you try with a another type array like String then overload is possible.

Correct me if i'm wrong.
 
GANESHKUMAR Parthsarathi
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My Guess is var arg also considered as an array type. That's why we are not able to overload with an array type of same int.

But if you try with a another type array like String then overload is possible.

Correct me if i'm wrong.
 
Ling Mike
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much!!

to: GANESHKUMAR
I think you are right.
method(int... i) and method(String[] s) are OK of course!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic