Java Enhanced for Loop

Source: Internet
Author: User
Tags iterable set set

3. Enhanced for Loop1) Function:

Iterate over the container of the storage object

2) How Jdk5 used to iterate 3) enhance the For loop iterative algebra Group

String [] arr = {"A", "B", "C"}; Static definition of an array, only when the array is first defined

Traditional way

for (int i=0; i<arr.length; i++) {

I, in turn, represent the array's Corner label

Strings = Arr[i];

System.out.println (s);

}

System.out.println ("-------------------------------------");

In Jdk5 we can use the enhanced for loop iteration

Enhanced for loop two arguments are written in parentheses, the first is declaring a variable, and the variable type must be the type of the array element

The second is a container that needs to be iterated

The For loop loops the length of the container, assigning the n-1 element of the container to the declared variable each time

for (String S:arr) {

Loop body, perform arr.length

Each time the n-1 element in Arr is given s

System.out.println (s); //

}

4) Single-row collection collection

List List = new ArrayList ();

List.add ("AAA");

List.add ("BBB");

List.add ("CCC");

Traditional Way 1

/* 1. Get iterators

Iterator iter = List.iterator ();

2. Loop to determine if the iterator has the next

while (Iter.hasnext ()) {

Stringstr = (String) iter.next (); Moves the pointer of the iterator to the next and returns the element that is currently pointing to the iteration

System.out.println (str);

}

*/

Traditional Way 2

For (Iterator iter=list.iterator (); Iter.hasnext ();) {

Strings = (String) iter.next ();

System.out.println (s);

}

System.out.println ("--------------------------------");

Enhanced for loop, does not use a generic collection can I use an enhanced for loop iteration? Yes

for (Object obj:list) {

Strings = (String) obj;

System.out.println (s);

}

5) Double Row set map

Map map = new HashMap ();

Map.put ("A", "AAA");

Map.put ("B", "BBB");

Map.put ("C", "CCC");

Traditional way Iteration 1

1. Get all the keys

Set keys = Map.keyset ();

2. Iterate keys to get all keys

Iterator iter = Keys.iterator ();

while (Iter.hasnext ()) {

Stringkey = (String) iter.next (); A b C

3. Obtain the corresponding value according to key

StringValue = (String) map.get (key);

System.out.println (key+ "=" + value);

}

System.out.println ("---------------------------------");

Traditional way 2, must master this way

1. Get all key-value pairs entry objects

Set Entrys = Map.entryset ();

2. Iterate through all entry

iter = Entrys.iterator ();

while (Iter.hasnext ()) {

Map.entryentry = (Entry) iter.next ();

Get key and value separately

Stringkey = (String) entry.getkey ();

StringValue = (String) entry.getvalue ();

System.out.println (key+ "=" + value);

}

System.out.println ("-------------------------------------");

SYSTEM.OUT.PRINTLN ("Enhanced for loop iteration,");

Enhanced for loop iterations,

In principle, the map collection cannot be iterated using the enhanced for loop,

Because the enhanced for loop can only iterate over a collection that implements the Iterable interface

Iterable is a newly defined interface in Jdk5, a method iterator method

Only the class that implements the Iterable interface can guarantee that there must be a iterator method

Java has such a qualification because it is enhanced internally by the For loop or by an iterator.

In fact, we can use the enhanced for loop in some way

For (Object Obj:map.entrySet ()) {

Obj in turn represents the entry

Map.entryentry = (Entry) obj;

System.out.println (Entry.getkey () + "=" + Entry.getvalue ());

}

6) Collection Iteration Attention issues

The collection cannot be deleted or removed during the iteration of the collection using iterators

@Test

public void Test4 () {

Listlist = new ArrayList ();

List.add ("Wangwu");

List.add ("Zhangsan");

List.add ("Lisi");

Iteratoriter = List.iterator ();

while (Iter.hasnext ()) {

Stringname = (String) iter.next ();

if ("Wangwu". Equals (name)) {

Delete from the collection

List.remove (name);

Methods to call iterators for deleting elements during an iteration

Iter.remove (); Delete the collection of my iterations the last element of my iteration

}

}

1 2 4

System.out.println (List.size ());

}

@Test

public void Test5 () {

Listlist = new ArrayList ();

List.add ("AA");

List.add ("BB");

Using Listiterator iterators

Listiteratorlistiterator = List.listiterator ();

while (Listiterator.hasnext ()) {

Listiterator.next ();

Adding elements during an iteration

Listiterator.add ("CC");

}

System. out. println (List.size ());

}

7) Enhanced for loop attention issues

element cannot be assigned when using enhanced for loop

Int[] arr = {A-i};

for (int num:arr) {

num= 0;

}

System.out.println (arr[1]);

Publicclass Demo3 {

@Test

public void Test3 () {

Map map=new HashMap ();

Map map2=newlinkedhashmap<k, v> ();

Map.put ("1", "AAA");

Map.put ("2", "BBB");

Map.put ("3", "CCC");

Traditional Way 1

Set Set=map.keyset ();

Iterator It=set.iterator ();

while (It.hasnext ()) {

stringkey= (String) it.next ();

Stringvalue= (String) map.get (key);

System.out.println ("key=" +key+ ", value=" +value);

}

Traditional Way 2

Set Set2=map.entryset ();

Iterator It2=set2.iterator ();

while (It2.hasnext ()) {

Map.entry entry= (Entry) it2.next ();

System.out.println ("key=" +entry.getkey () + ", value=" +entry.getvalue ());

}

1 ways to enhance a For loop

For (Object Obj:map.keySet ()) {

stringkey2= (String) obj;

Stringvalue2= (String) map.get (Key2);

System.out.println ("key2=" +key2+ ", value2=" +value2);

}

2 ways to enhance A For loop

For (Objectobj:map.entrySet ()) {

map.entryentry3= (Entry) obj;

String key3= (String) Entry3.getkey ();

stringvalue3= (String) entry3.getvalue ();

System.out.println ("key3=" +key3+ ", value3=" +value3);

}

Issues to be aware of when enhancing for loops: data only

int arr[]={1,2,3};

for (int i:arr) {

i=10;

}

System.out.println (arr[0]);//1

List li=new ArrayList ();

Li.add ("1");

for (Object Obj:li) {

obj= "888";

}

System.out.println (li.get (0));//1

}

}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java Enhanced for Loop

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.