Set the output

This is the 20th day of my participation in the August Text Challenge.More challenges in August

The standard output for collections in the class framework is: Iterator, ListIterator, Enumeration, foreach;

Iterator output:

Iterating output: Judge each element in turn to see if it has content and output if it does.

Iterator is instantiated by iterate() of Iterable.

Methods for Iterator:

boolean hasNext() Returns true if the iteration has more elements.
E next() Returns the next element in the iteration.
default void remove() Removes the last element returned by this iterator from the underlying collection (optional operation).
boolean hasNext() Returns true if the iteration has more elements.

Example:

packageJava from entry to project practice. Java class set framework. Set output;import java.util.Iterator;
import java.util.Set;
public class IteratorThe outputSetA collection of{
    public static void main(String[] args) {
        Set<String> all = Set.of("Hello"."World"."xbhog");
        Iterator<String> iter = all.iterator();
        while(iter.hasNext()){
            String str = iter.next();
            System.out.print(str+"、"); }}}Copy the code

About data deletion:

Both collections and iterators have remove methods; So what to choose:

The Collection features:

  • No matter what, I just deleted it for you, which would causeJava.util.ConcurrentModificationExceptionError;

The Iterator features:

  • During iteration, judgment is made according to the stored data content. So only remove in the Iterator interface is the correct way to implement removing data.

Such as:

package cn.mldn.demo;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class JavaCollectDemo {
	public static void main(String[] args) {
		// Collections created with set.of () or list.of () cannot be deleted
		Set<String> all = new HashSet<String>();
		all.add("White");					// Save data
		all.add("Java");					// Save data
		all.add("Java"); 					// Save duplicate data
		all.add("xbhog");				// Save data
		Iterator<String> iter = all.iterator(); 
		while (iter.hasNext()) {				// Whether the set has data
			String str = iter.next();			// Get data
			if ("Java".equals(str)) {
				iter.remove() ; 				// Delete current data
			} else {
				System.out.print(str + "、"); }}}}Copy the code

ListIterator bidirectional iteration:

First, distinguish the Iterator’s purpose:

Iterator does a one-way, front-to-back output

ListIterator does output from back to front

But ListIterator can only be written backwards if Iterator is written backwards (note the order);

Because the pointer does not execute last until the end of the implementation of the forward to backward output;

If the order is reversed, the output is null.

The following expansion method:

Modifier and Type Method Description
boolean hasPrevious() Returns true if the list iterator has more elements as it moves backwards through the list.
E previous() Returns the previous element in the list and moves the cursor back.

Example: Perform bidirectional iteration

packageJava from entry to project practice. Java class set framework. Set output;import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
public classBidirectional iteration outputListIterator {
    public static void main(String[] args) {
        List<String> all = new ArrayList<String>();
        all.add("Xiao li");
        all.add("Song");
        all.add("xbhog");
        ListIterator<String> iter = all.listIterator();
        System.out.println("To perform a backward-forward operation, you must first perform a front-to-back operation so that the pointer points backwards.");
        // If you do not follow the relevant operation, the output from the back to the front is empty;
        System.out.println("Output from front to back: -----------");
        while(iter.hasNext()){
            System.out.println(iter.next());
        }
        System.out.println("Output from back to front: ------------");
        while(iter.hasPrevious()){  // Determine if the previous element exists
            System.out.println(iter.previous());  // Some output the previous element}}}Copy the code

The ListIterator interface implements bidirectional iteration of a List collection.

Enumeration Enumeration output:

The output of this type is built on a Vector collection; Equivalent to attached products;

Its common interface methods:

Modifier and Type Method Description
boolean hasMoreElements() Tests whether this enumeration contains more elements.
E nextElement() Returns the next element of the enumeration if the enumeration object has at least one more element to supply.

Example: Output vector collection data

package cn.mldn.demo;
import java.util.Enumeration;
import java.util.Vector;
public class JavaCollectDemo {
	public static void main(String[] args) {
		Vector<String> all = new Vector<String>(); 		// instantiate Vector
		all.add("Yellow");								// Save data
		all.add("Java");								// Save data
		all.add("xbhog");							// Save data
		Enumeration<String> enu = all.elements() ;			// Get an Enumeration instance
		while (enu.hasMoreElements()) {
			String str = enu.nextElement() ;
			System.out.print(str + "、"); }}}Copy the code

Note that Enumeration is an output operation but not a delete operation.

The foreach output:

Not much to say, can realize array output, also support collection output;

package cn.mldn.demo;
import java.util.HashSet;
import java.util.Set;
public class JavaCollectDemo {
	public static void main(String[] args) {
		Set<String> all = new HashSet<String>(); 			// instantiate Set
		all.add("Yellow");								// Save data
		all.add("Java");								// Save data
		all.add("xbhog");							// Save data
		for (String str : all) {
			System.out.print(str + "、"); }}}Copy the code

To implement custom foreach output:

The first thing you need to know is that implementing foreach requires support from the Iterator interface. That’s why foreach can be used to output sets and lists.

If we want to implement the output of a custom class ourselves, we need to instantiate the Iterable interface to do iterator’s job.

package cn.mldn.demo;
import java.util.Iterator;
class Message implements 可迭代<String> {// Support foreach output
	private String[] content = { "Java"."Python"."Ubuntu" }; 	// Information content
	private int foot; 					// Operate the pin
	@Override
	public Iterator<String> iterator(a) {	// Get an instance of Iterator
		return new MessageIterator();
	}
	private class MessageIterator implements Iterator<String> {
		@Override
		public boolean hasNext(a) {		// Determine if content exists
			return Message.this.foot < 
				Message.this.content.length;
		}
		@Override
		public String next(a) {			// Get data
			return Message.this.content[Message.this.foot++]; }}}public class JavaCollectDemo {
	public static void main(String[] args) {
		Message message = new Message();	// Iterable interface instances
		for (String msg : message) {		/ / foreach output
			System.out.print(msg + "、"); }}}Copy the code

The end:

If you see here or just to help you, I hope you can click 👍 or ★, thank you;

There are mistakes, welcome to point out in the comments, the author will see the modification.