java中不定长参数的实例用法
作者:angryTom 时间:2021-06-17 02:49:35
java中不定长参数的使用方法
不定长参数方法的语法如下:
返回值 方法名(参数类型...参数名称)
在参数列表中使用“...”形式定义不定长参数,其实这个不定长参数a就是一个数组,编译器会将(int...a)这种形式看作是(int[] a)的形式。
示例:编写一个不定长参数方法。
/**
* 定义不定长参数方法
*
* @author pan_junbiao
*
*/
public class MyTest
{
public static int add(int... a)
{
int s = 0;
for (int i = 0; i < a.length; i++)
{
s += a[i];
}
return s;
}
public static void main(String[] args)
{
// 调用不定长参数方法
System.out.println("调用不定长参数方法:" + add(1, 2, 3, 4, 5, 6, 7, 8, 9));
System.out.println("调用不定长参数方法:" + add(1, 2));
}
}
运行结果:
调用不定长参数方法:45
调用不定长参数方法:3
知识点扩展:
可变长参数的使用规则
在调用方法的时候,如果能够和固定参数的方法匹配,也能够与可变长参数的方法匹配,则选择固定参数的方法。看下面代码的输出:
package com;
// 这里使用了静态导入
import static java.lang.System.out;
public class VarArgsTest {
public void print(String... args) {
for (int i = 0; i < args.length; i++) {
out.println(args[i]);
}
}
public void print(String test) {
out.println("----------");
}
public static void main(String[] args) {
VarArgsTest test = new VarArgsTest();
test.print("hello");
test.print("hello", "alexia");
}
}
来源:https://www.php.cn/java-article-441992.html
标签:java,长参数
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Android开发之ListView列表刷新和加载更多实现方法
2021-06-20 06:28:30
![](https://img.aspxhome.com/file/2023/9/94949_0s.png)
Android使用xUtils3.0实现文件上传
2023-08-04 19:50:02
SpringBoot整合Mybatis与druid实现流程详解
2022-09-17 17:05:31
![](https://img.aspxhome.com/file/2023/4/118824_0s.png)
Android实现图片点击爆炸效果
2023-06-04 04:18:55
![](https://img.aspxhome.com/file/2023/8/98668_0s.gif)
Java中自动生成构造方法详解
2023-06-21 14:17:44
Centos中安装jdk案例讲解
2023-04-30 00:37:50
![](https://img.aspxhome.com/file/2023/5/74975_0s.png)
树莓派.GPRS.短信接收器
2021-11-01 08:34:31
![](https://img.aspxhome.com/file/2023/1/96091_0s.png)
浅谈Java常见的排序算法
2023-09-08 11:11:11
![](https://img.aspxhome.com/file/2023/0/63640_0s.png)
Unity通用泛型单例设计模式(普通型和继承自MonoBehaviour)
2023-08-24 14:53:28
再谈java回调函数
2023-09-27 19:20:10
C#根据日期计算星期几的实例代码
2021-07-24 21:43:34
C# JSON格式化转换辅助类 ConvertJson
2023-09-27 19:40:20
Java Spring Dubbo三种SPI机制的区别
2022-05-04 00:29:51
Java 获取当前系统时间的三种方法
2023-11-21 12:51:51
Android客户端post请求服务器端实例
2022-10-10 23:49:43
![](https://img.aspxhome.com/file/2023/8/93308_0s.png)
实例讲解Android多线程应用开发中Handler的使用
2021-11-23 03:23:13
![](https://img.aspxhome.com/file/2023/3/113293_0s.jpg)
Java动态规划之编辑距离问题示例代码
2023-10-30 00:21:21
![](https://img.aspxhome.com/file/2023/1/84781_0s.gif)
详解Spring Boot加载properties和yml配置文件
2023-11-24 07:14:09
Android获取手机电池电量用法实例
2021-08-05 23:14:34
![](https://img.aspxhome.com/file/2023/3/110763_0s.png)
spring中bean的生命周期详解
2021-11-29 23:31:02