黑马程序员——JAVA基础之JDK1.5新特性高级for循环和可变参数

时间:2023-02-18 12:02:52

------- android培训java培训、期待与您交流! ----------

 

 

高级for循环
 
格式:

 
for(数据类型 变量名 : 被遍历的集合(Collection)或者数组)
{
    

 

for循环和迭代器在集合中的区别:

 

对集合进行遍历。只能获取集合元素。但是不能对集合进行操作。
 
迭代器除了遍历,还可以进行remove集合中元素的动作。如果是用ListIterator,还可以在遍历过程中对集合进行增删改查的动作。

 
 
传统for和高级for有什么区别呢?
 
高级for有一个局限性。必须有被遍历的目标。
 
建议在遍历数组的时候,还是希望是用传统for。因为传统for可以定义脚标。

 

import java.util.ArrayList;


class ForEachDemo
{
public static void main(String[] args)
{
ArrayList<String> al = new ArrayList<String>();

al.add("abc1");
al.add("abc2");
al.add("abc3");

for(String s : al)
{
System.out.println(s);
}

System.out.println(al);
}
}


 

class ForEachDemo 
{
public static void main(String[] args)
{
int[] arr = {3,5,1};

for(int x=0; x<arr.length; x++)
{
System.out.println(arr[x]);
}

for(int i : arr)
{
System.out.println("i:"+i);
}
}
}


 

import java.util.HashMap;
import java.util.Map;
import java.util.Set;


class ForEachDemo
{
public static void main(String[] args)
{
HashMap<Integer,String> hm = new HashMap<Integer,String>();

hm.put(1,"a");
hm.put(2,"b");
hm.put(3,"c");

Set<Integer> keySet = hm.keySet();
for(Integer i : keySet)
{
System.out.println(i+"::"+hm.get(i));
}

for(Map.Entry<Integer,String> me : hm.entrySet())
{
System.out.println(me.getKey()+"------"+me.getValue());
}

}
}


 
方法的可变参数:

        在使用时注意:可变参数一定要定义在参数列表最后面。

 
可变参数: 

        其实就是上一种数组参数的简写形式。不用每一次都手动的建立数组对象。

        只要将要操作的元素作为参数传递即可。隐式将这些参数封装成了数组。

 

class  ParamMethodDemo  
{
public static void main(String[] args)
{
show("haha",2,3,4,5,6);
}
public static void show(String str,int... arr)
{
System.out.println(arr.length);
}
}


 

 

------- android培训java培训、期待与您交流! ----------