Access Methods for Collections in Java

Given the general class:

class MyClass (
       private List l = new LinkedList <String>();

       public void addElement (String s) (l.add (s);)
       .............
)

an access method that allows me to iterate over the list the way it should be?

I decided to implement a method that returns an iterator directly, but does not seem to be correct, because it can change the list from the outside using remove ().

What do you think?

+3
source share
4 answers
import java.util.*;

public Iterator<String> elements() {
  return Collections.unmodifiableList(elements).iterator();
}

If you don't mind that the items are stored as a list, you can also use do:

public ListIterator<String> elements() {
  return Collections.unmodifiableList(elements).listIterator();
}

If you want to allow callers to use the foreach syntax, you can return Iterable:

public Iterable<String> getElements() {
  return Collections.unmodifiableList(elements);
}

And again, if you do not mind that the elements are returned as a list, this last decision could return List<String>

+4
source

Iterable, remove, NamshubWriter get(index) size() (, List). .

0

but would such a thing be perfect?

public Iterator<String> getList(){

    return new Iterator<String>(){
        Iterator<String> i=l.iterator();

        public boolean hasNext() {              
            return i.hasNext();
        }

        public String next() {
            if(!i.hasNext()) throw new NoSuchElementException();

            return i.next();
        }

        public void remove() {
            throw new UnsupportedOperationException();              
        }


    }
}
0
source

I need a method that allows me to simply browse through the elements of the collection and save the encapsulation, the method cannot be verified ... I know, but I can’t use it.

0
source

Source: https://habr.com/ru/post/1751890/


All Articles