Java数组和foreach遍历循环

Java中的foreach遍历用法 它提供了一种更简洁、更易读的方式来遍历集合中的元素,而无需使用传统的for循环和索引变量。在一些情况下,我们可能需要在foreach循环中修改集合中的元素。然而,由于foreach循环的工作原理是基于迭代器的,它并不提供直接修改集合元素的方式。在这个语法结构中,元素类型是要遍历的数组或集合中元素的类型,而元素变量是用于引用当前遍历到的元素的变量名。在每次循环迭代时,元素变量将自动被赋值为当前遍历到的元素,然后可以在循环体中使用。的整型数组,并使用foreach循环遍历数组中的每个元素。,然后将其打印输出。 阅读详情

数组由多个元素组成,每个元素都具有相同数据类型。

一维数组

int intArrayOne[]; //定义一个一维数组
int intArrayTwo[] = {1,2,3,4,5}; //静态初始化一个数组
intArrayOne = new int[5]; //动态初始化数组

intArrayOne[3]=10; //给intArrayOne的第4个元素赋值为10
System.out.println(intArrayOne[0]);//引用intArrayOne数组中的第1个元素并进行输出,因为此时第1个元素还被赋值,所以其值为整型的默认值0,输出为0
System.out.println(intArrayOne[3]);//引用intArrayOne数组中的第4个元素并进行输出
System.out.println(intArrayTwo[4]);//引用intArrayTwo数组中的第5个元素并进行输出
/*
    静态初始化在声明一个数组变量的同时,进行赋值;动态初始化给一个已存在的数组类型的变量赋一个空的数组,两种方法在初始化后,
    变量所存储的数组的元素数目都是确定的,使用下标进行引用时不能超过其范围
*/

foreach遍历循环

/*
    语法:
    for(元素类型 临时变量名:遍历对象){
        引用了临时变量的语句(临时变量存入的是遍历对象中的元素,而非元素对应的下标)
    }
*/
//for循环输出一个数组中的所有元素
for(int i=0;i<=intArrayTwo.length-1;i++){
    System.out.println(intArrayTwo[i]);
}

//可以使用便利循环进行简化
for(int num:intArrayTwo){
    System.out.println(num);
}

多维数组

/*
    以二维数组为例,二维数组可以看作是数组的数组,它里面的每一个元素都是一个数组,
    且这些数组的数据类型必须相同,但每个数组的大小可以不同
*/

//二维数组的声明与初始化
int intArrayOne[][] = {{1,2},{2,3},{3,4,5}};//静态初始化
int intArrayTwo[][];
int intArrayThree[][];
//一次性为每一维分配空间
intArrayTwo new = int[3][2]; //intArrayTwo数组共可以含有3个数组元素,其中每个数组元素都可以且只能含有两个整数

//从最高维开始,分别为每一维分配空间
intArrayThree = new int[3][];//intArrayThree数组共含三个数组元素
intArrayThree[0] = new int[2];//第一个数组元素,可存储2个元素
intArrayThree[1] = new int[3];//第二个数组元素,可存储3个元素
intArrayThree[2] = new int[5];//第三个数组元素,可存储5个元素

//二维数组元素的引用
int num[][]=new int[2][];
num[0]=new int[2];
num[1]=new int[3];
num[0][0]=1;
num[0][1]=2;
num[1][0]=3;
num[1][1]=4;
num[1][2]=5;
System.out.println(num[0][1]);//输出num二维数组的第一个数组元素的第二个元素

二维遍历循环:

int numArray[][]={{1,2,3},{2,3,4},{4,5}};
for(int[] intArray:numArray){
    for(int num:intArray){
        System.out.println(num);
    }
}
//输出所有元素
Java数组遍历——使用foreach循环 在上面的代码中,我们声明了一个整型数组numbers,并初始化了一些值。然后,我们使用foreach循环遍历该数组,并通过System.out.println()方法打印出每个字符串元素的值。如果你需要遍历其他类型的集合,例如ArrayList,你仍然需要使用传统的for循环。在传统的for循环中,我们需要使用索引来迭代数组中的每个元素。然而,使用foreach循环,我们可以更加简洁地遍历数组,无需关心索引。除了整型数组,我们也可以使用foreach循环遍历其他类型的数组,例如字符串数组、对象数组等。 阅读详情

相关推荐

国民技术N32G45X SysTick定时器实战:从1us到100ms的精准延迟实现(附完整代码)

本文详细解析了国民技术N32G45X芯片中SysTick定时器的工作原理,并提供了从1微秒到100毫秒的高精度延迟实现方案。通过对比官方库函数的局限性,文章重点介绍了无中断查询模式、时钟源选择策略以及完整的代码实现,帮助嵌入式开发者精准控制时序,适用于LED控制、软件模拟通信协议等多种实战场景。

weixin_29190573的博客 372

forEach( )遍历数组方法 之(多种说法)

forEach( )遍历数组方法 之(多种说法)

m0_64494670的博客 5723

Android Qcom USB Driver学习(十三)

该系列文章总目录链接与各部分简介: Android Qcom USB Driver学习(零) Android Qcom USB Driver学习(八) Android Qcom USB Driver学习(九)deals with the USB Power Delivery resources used by one or more ports on the basis of the local device policy the basis of the local device policy.opera

Android驱动开发 2611

foreach遍历数组的两种方法

使用foreach遍历数组时,要知道其中的两种方法,熟练掌握

living_ren的博客 2万+

PX4环境git submodule update --init --recursive失败的解决办法

最近开始搭建PX4环境,搭建是需要从github下载工程,然后使用语句git submodule update --init --recursive更新工程子模块,但往往由于网络原因这一步需要很久,甚至会失败。因为github是外网,在上面下载代码会受到很大限制,往往会出现下面的问题: 即无法连接到github,查阅了相关资料后,我发现了解决更新子模块失败的方法: 1.打开你下载的PX4源码,即Firmware文件夹,找到其中的.gitmodules,如下图: 2…gitmodules有以上格式,path

qq_36903625的博客 1万+

从流体力学到深度学习:手把手教你用PINN预测涡流场(基于TensorFlow2.10+GPU)

本文详细介绍了如何利用物理信息神经网络(PINN)结合TensorFlow 2.10和GPU加速,预测Navier-Stokes方程的涡流场。通过核心原理讲解、实战环境配置、网络架构设计及物理约束实现,帮助读者掌握从流体力学到深度学习的跨学科技术应用,特别适合处理复杂流体问题和非定常流动场景。

weixin_29048309的博客 211

遍历数组的一些方法

js提供了多种遍历数组的方法,在此简单介绍一下 一,forEach方法 forEach常用的数组遍历方法,它提供一个回调函数,可用于处理数组的每一个元素,默认没有返回值,不影响元素本身。 forEach从头到尾遍历数组,改变数组本身,参数依次是数组元素,元素索引,数组本身。 var arr = [1, 2, 3, 4, 5]; arr.forEach(functio...

weixin_46799584的博客 1903

并网逆变器学习笔记8---平衡桥(独立中线模块)控制

参考文献:《带独立中线模块的三相四线制逆变器中线电压脉动抑制方法》---赵文心。

圆桌骑士的博客 7301

foreach 二维java_教你如何用for和foreach循环遍历java中的二维数组

一:先来说说for和foreach循环的区别for和foreach的区别foreach语句是java5的新特征之一,在遍历数组、集合方面,foreach为开发人员提供了极大的方便。foreach语句是for语句的特殊简化版本,但是foreach语句并不能完全取代for语句,然而,任何的foreach语句都可以改写为for语句版本。foreach并不是一个关键字,习惯上将这种特殊的for语句格式称之...

weixin_29733795的博客 1902

从零构建高精度电子秤:HX711与STM32的时序通信陷阱与实战避坑指南

本文详细解析了使用STM32F103C8T6与HX711模块构建高精度电子秤的通信时序陷阱与实战解决方案。重点探讨了微秒级延迟实现、数据读取算法、校准方法和滤波优化,帮助开发者避开常见通信问题,提升电子秤的测量精度和稳定性。

data3的博客 781

SOEM主站开发篇(1):移植SOEM主站到Linux开发板

详细介绍了SOEM主站源码移植到Linux开发板上的步骤,同时演示了如何使用Linux开发板获取EtherCAT从站的PDO映射信息。

kevin1499的博客 2395

Java集合之新特性 foreach 循环遍历集合或数组(四)

Java 5.0新特性 foreach 循环遍历集合或数组

m0_49124752的博客 732

通信算法之334:无人机侦测-DJI 大疆云哨接收机系列

【代码】通信算法之334:DJI 大疆 云哨接收机算法流程。

leegang12的专栏 843

java 数组遍历_Java中遍历数组使用foreach循环还是for循环?

从JDK1.5起,增加了新功能Foreach,它是for循环遍历数据的一种简写形式,使用的关键字依然是for,但参数格式不同。其详细用法为:for(Type e:collection){//对变量e的使用}参数说明:e:其类型Type是集合或数组中元素值的类型,该参数是集合或数组collection中的一个元素。collections: 要遍历的集合或数组,也可以是迭代器。在循环体中使用参数e,该...

weixin_35916710的博客 294

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

Java中foreach和for在循环遍历数组、集合方面的区别

自从Java5中引入了foreach语句之后,在循环遍历数组、集合方面带来了极大的方便,但是在用foreach的时候也要注意其与for循环是不能完全划等号的。

michaelhuaqing的专栏 5358

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

java中foreach循环遍历二维数组_php如何遍历二维数组

官方文档中给了foreach的两种用法foreach 语法结构提供了遍历数组的简单方式。foreach 仅能够应用于数组和对象,如果尝试应用于其他数据类型的变量,或者未初始化的变量将发出错误信息。有两种语法:foreach (array_expression as $value)statementforeach (array_expression as $key => $value)stat...

weixin_39671405的博客 985

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Java的foreach循环(增强型for循环)是Java 5引入的语法糖,主要用于简化集合和数组的遍历操作。以下从工作原理、使用场景、限制及效率等方面说说

​推荐使用仅需读取元素,无需修改集合结构代码简洁性优先的场景(如快速调试输出)遍历链表结构(如LinkedList​避免使用需要增删集合元素需要获取元素索引对性能有极致要求(如超大规模数组遍历)通过合理选择循环方式,可提升代码可读性和运行效率。对于复杂操作,建议结合迭代器或Java 8的Stream API实现更灵活的控制。

m0_75236543的博客 1284

java中foreach循环遍历二维数组_foreach for循环遍历数组,List

[java]代码库/*** 对整数数组求和*/public static long getSum(int[] nums) throws Exception {if (nums == null) {throw new Exception("错误的参数输入,不能为null!");}long sum = 0;// 依次取得nums元素的值并累加for (int x : nums) {sum += x;}...

weixin_31090341的博客 593

java foreach循环 初始化数组_【汇总】java中数组的声明、初始化及遍历

java中数组用来存储固定大小的同类型元素一维数组:1.数组的声明://声明一维数组,推荐用第一种int[] a;int b[];2.数据的初始化:有三种初始化方式(1).静态初始化//静态初始化int[] a = {1,2,3}(2).用new声明,之后分别初始化数组中的每个元素,声明时需指定数组大小int[] a = new int[3];a[0] = 1;a[1] = 2;a[2] = 3;...

weixin_30290131的博客 705

foreach遍历二维数组java_java关于集合的遍历与增强for循环(foreach)的使用

1 //增强For循环2 public class MapTest {34 public static void main(String[] args) {5 // 创建一个HashMap对象,并加入了一些键值对。6 Map maps = new HashMap();7 maps.put("111", "java111");8 ...

weixin_28985877的博客 218

java foreach list_java foreach for循环遍历数组,List

[java]代码库/*** 对整数数组求和*/public static long getSum(int[] nums) throws Exception {if (nums == null) {throw new Exception("错误的参数输入,不能为null!");}long sum = 0;// 依次取得nums元素的值并累加for (int x : nums) {sum += x;}...

weixin_42512723的博客 370

foreach循环遍历

使用foreach循环遍历集合元素: 1)Java5.0 提供了foreach循环迭代访问Collection和数组。 2)遍历操作不需要获取Collection或数组的长度,无需使用索引访问元素。 3)遍历集合的底层调用Iterator完成操作 4)foreach还可以用来遍历数组 for(Person person: person){ //for(要遍历的元素类型 遍历后自定义元素名称:要遍历的结构名称) System.out...

来杯奶茶 4040

JAVA--Array--foreach循环

foreach循环一般是用来打印出数组的 案例 package com.guo.operator.array; public class ArrayDemo03 { public static void main(String[] args) { int[] array = {1,2,3,4,5}; //For-each循环(一般是用来打印输出一些结果) jdk1.5 没有下标 // for (int i : array) { //

weixin_44529105的博客 608

Java--foreach循环

Java–foreach循环 foreach是Java5新增,在遍历数组,集合的时候有不错的性能. foreach的语法格式: for(元素类型 每次循环的元素名称 : 循环对象){ } 一.常见的使用方式     1.遍历数组 public static void main(String[] args) { String[] ...

WGS. 1万+

java数组------数组的遍历foreach循环

package cn.zxg.arrays;/** * 通过foreach读取数组中的元素 */public class Test03 { public static void main(String[] args) { int [] arr=new int[10]; //动态初始化数组 for(int i=0;i<arr.length;i++...

weixin_30385925的博客 225

深究Java foreach循环的实现原理和其中的坑

集合、数组的遍历是必不可少的开发工具,foreach又是那么甜,二者走到一起会发生什么呢?这篇文章带你一起尝一尝其中的酸甜苦辣!

衷水木先生的博客 4428
上一篇: Java分支流程和循环
下一篇: 综合练习: 九九乘法表和排序
a_good_programer
博客等级 码龄10年 18粉丝 35原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值