Iterator print LinkedList - java

I have a problem regarding the display of my LinkedList with a foreach.
When I want to display my LikedList an error comes from my list which tells me that I have to use an iterator. Here is the code:
public class Set {
private LinkedList <Integer> elements;
public Set () {
this.elements = new LinkedList <Integer> ();
}
public static void main (String [] args) {
Set test = new Set ();
test.add (8);
test.add (2);
test.add (7);
for (int e: test) {
}
}
So I used an iterator for the display but a message tells me that my iterator is undefined for the method set.
Here is the code:
public class Set {
private LinkedList <Integer> elements;
public Set () {
this.elements = new LinkedList <Integer> ();
}
public static void main (String [] args) {
Set test = new Set ();
test.add (8);
test.add (2);
test.add (7);
Iterator <Integer> iterator = test.iterator ();
while (iterator.hasNext ()) {
System.out.println (iterator.next ());
}
}
If you can help me with that, it will help me a lot.
(I tried to define "Iterator <Integer> iterator = this.elements.iterator ();" in the Set () public and call it in the hand that way but without success "while (iterator.hasNext ()) {
System.out.println (iterator.next ());
}")
Thank you in advance, nice day

Your Set class needs to implement iterable interface as
public class Set implements Iterable<Integer> {
private LinkedList<Integer> elements;
public Set() {
this.elements = new LinkedList<Integer>();
}
#Override
public Iterator<Integer> iterator() {
return elements.iterator();
}
}

Your class Set doesn't define an iterator you should add for example a method like that one:
public Iterator<Integer> getIterator() {
return elements.iterator();
}

Related

Custom iterator won't print anything when trying to iterate through an ArrayList

I'm very new to iterators but for an assignment I wrote a custom Iterator and I want to simply print out object as I iterate through a list of them but it keeps printing nothing and I have no idea why.
Here's the custom iterator code:
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
public class MyList<T> implements Iterable<T> {
private List<T> list;
private class MyIterator<t> implements Iterator<t> {
int lSize = list.size();
int lPoint = 0;
public boolean hasNext() {
return (lPoint < lSize);
}
public t next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
t val = (t) list.get(lPoint);
lPoint++;
return val;
}
}
public MyList(List<T> list) {
this.list = list;
}
public Iterator<T> iterator() {
return new MyIterator<>();
}
}
Here's the class I'm using to test it:
Public class TestCloning {
Electronics test = new Electronics("Test", 100, 10);
Electronics test3 = new Electronics("Test2", 300, 30);
List<Electronics> order1 = new ArrayList<>();
MyList<Electronics> mList1 = new MyList<>(order1);
Iterator<Electronics> mIterator1 = mList1.iterator();
public void testIterator(){
order1.add(test);
order1.add(test3);
while (mIterator1.hasNext()){
System.out.println(mIterator1.next().toString());
}
}
}
This is mainly because the lSize=0
The reason why it is zero is because you add the list of things to myList before you actually add any items into that list.
List<String> order1 = new ArrayList<>();
order1.add(test);
order1.add(test3);
MyList<String> mList1 = new MyList<>(order1);
Iterator<String> mIterator1 = mList1.iterator();
If you flip the order, add things to the order list, then create your custom one everything will work as you'd expect.
Also, I suggest in the future, don't use any custom iterators or lists that wrap normal lists. I understand this is for the purpose of an assignment, and then acceptable

How to remove element from private ArrayList in generic class

I have generic class MyArray where private member is ArrayList, and inside is implemented iterator.
In Main is given some MyArray with strings and I want to delete all "test" from it... Problem is in iterator which method remove doesn't work
Here is how class looks like:
public class MyArray<E> {
private ArrayList<E> list;
public MyArray() {
list = new ArrayList<E>();
}
public int length() { return list.size(); }
public E at(int pos) { return list.get(pos); }
public void add(E val) { list.add(val); }
public void remove(int pos) { list.remove(pos); }
public class MyIterator implements Iterator<E>{
int index;
#Override
public boolean hasNext() {
return index < list.size();
}
#Override
public E next() {
if (!hasNext())
throw new NoSuchElementException("no next value");
E tmp = list.get(index);
index++;
return tmp;
}
}
public Iterator<E> iterator() {
return new MyIterator();
}
public static void main(String[] args) {
MyArray<String> b = new MyArray<String>();
b.add("This");
b.add("is");
b.add("test");
b.add("please");
b.add("delete");
b.add("all");
b.add("test");
Iterator<String> iter = b.iterator();
while(iter.hasNext())
System.out.println(iter.next());
for(Iterator<String> i = b.iterator(); i.hasNext(); ) {
String tmp = i.next();
if (tmp.equals("test"))
i.remove();
}
Iterator<String> ite = b.iterator();
while(ite.hasNext())
System.out.println(ite.next());
}
}
Exception that I get is:
Exception in thread "main" java.lang.UnsupportedOperationException: remove
at java.util.Iterator.remove(Unknown Source)
at cas1.MyArray.main(MyArray.java:71)
You need to override remove() in your Iterator.
However, it'd be easiest to make your iterator() method return list.iterator(), rather than implementing it yourself:
public Iterator<E> iterator() {
return list.iterator();
}
Iterator in an interface, and you need to implement each of the Iterator methods in MyIterator that you intend to call.
MyIterator that you defined doesn't override Iterator.remove() and
the remove() defined in the Iterator interface is defined as a default method that throws UnsupportedOperationException :
default void remove() {
throw new UnsupportedOperationException("remove");
}
So override it simply to remove effectively the iterated element.
You can rely on ArrayList.Itr code :
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}

Implementing a List data structure in java

I have a homework about implementing lists in java. I have written a code, and a method about displaying the elements, but when I run it, it says there is an error in this method. can you please help me fix this?
here is my code:
public class Lista {
public int num;
public Lista pas;
public Lista(int num){
this.num = num;
}
public void display(){
System.out.println(num);
}
public static void main(String[] args){
linkedList l = new linkedList();
l.insertfirst(1);
l.insertfirst(3);
l.insertfirst(5);
l.display();
}
}
class linkedList{
public Lista LIST;
public Lista pozicion;
linkedList(){
LIST = null;
}
public void insert(int num, Lista pozicion){
Lista temp = pozicion.pas;
Lista l = new Lista(num);
pozicion.pas.num = num;
pozicion.pas.pas = temp;
}
public void delete(Lista pozicion){
pozicion.pas = pozicion.pas.pas;
}
public Lista locate(int num, Lista LIST){
pozicion = LIST;
while (pozicion.pas != null){
if (pozicion.pas.num == num){
return pozicion;
}else{
pozicion = pozicion.pas;
}
}
return pozicion;
}
public void insertfirst(int num){
Lista eRe = new Lista(num);
eRe.pas = LIST;
LIST = eRe;
}
}
Well, for starters...
display() is not a method of class linkedList (note: naming convention should be LinkedList).
display() is a method of Lista. That is why the IDE is telling you 'display() is undefined for the type linkedList'
Just quickly looking at your code for what you need to do... You need to implement a get() (or perhaps a solution to get the first element of the linkedList and from there iterate through the linkedList) method in the linkedList class which returns a Lista object. With that Lista object, you can then call the method .display() on it.

How to reverse an unmodifiable List in java

I am trying to reverse an unmodifiable list. However i have tried to achieve it but Is it possible to update or reverse and unmodifiable list? I know we can do it with Google Immutable List
import java.util.*;
public class ImmutableList
{
public static void main(String args[])
{
String[] mylist = {"Apple","Orange","Mango","Kiwi","Banana"};
List reverselist = new ArrayList();
List<String> strList = Arrays.asList(mylist);
List<String> unmodifiableList = Collections.unmodifiableList(strList);
for(int i=unmodifiableList.size();i>0;i--)
{
reverselist.add(unmodifiableList.get(i-1));
}
List<String> reverse = Collections.unmodifiableList(reverselist);
System.out.println(reverse);
}
}
In the above program I am just traversing in unmodifable list from back and putting them in an array after that adding that array to new unmodifiable list. Can we do it in better way in terms of optimisation?
Guava's Lists.reverse(List) returns a reversed view of the original list, without doing any copying.
When the list is unmodifiable anyhow, you can just create a reversed view on the list.
This is optimal in terms of performance and storage: It requires O(1) time and O(1) additional space to create this list.
import java.util.AbstractList;
import java.util.Arrays;
import java.util.List;
public class ReversedListViewTest
{
public static void main(String[] args)
{
String[] array = {"Apple","Orange","Mango","Kiwi","Banana"};
List<String> list = Arrays.asList(array);
System.out.println("List : "+list);
List<String> reversedView = reversedView(list);
System.out.println("Reversed view: "+reversedView);
}
private static <T> List<T> reversedView(final List<T> list)
{
return new AbstractList<T>()
{
#Override
public T get(int index)
{
return list.get(list.size()-1-index);
}
#Override
public int size()
{
return list.size();
}
};
}
}
May be not the best solution but better then reverse ourself:
public List<T> reverseUnModList(List<T> unModListOrig) {
List<T> tmpList = new ArrayList<T>(unModListOrig);
Collections.reverse(tmpList);
return Collections.unmodifiableList(unModListOrig);
//return tmpList; //if the result not need to be unmodifieable
}

How to implement iterator as an attribute of a class in Java

let's say I have this simple MyArray class, with two simple methods: add, delete and an iterator. In the main method we can see how it is supposed to be used:
public class MyArray {
int start;
int end;
int[] arr;
myIterator it;
public MyArray(){
this.start=0;
this.end=0;
this.arr=new int[500];
it=new myIterator();
}
public void add(int el){
this.arr[this.end]=el;
this.end++;
}
public void delete(){
this.arr[this.start]=0;
this.start++;
}
public static void main(String[] args){
MyArray m=new MyArray();
m.add(3);
m.add(299);
m.add(19);
m.add(27);
while(m.it.hasNext()){
System.out.println(m.it.next());
}
}
And then MyIterator should be implemented somehow:
import java.util.Iterator;
public class myIterator implements Iterator{
#Override
public boolean hasNext() {
// TODO Auto-generated method stub
return false;
}
#Override
public Object next() {
// TODO Auto-generated method stub
return null;
}
#Override
public void remove() {
// TODO Auto-generated method stub
}
}
MyIterator should iterate arr from MyArray class, from start to end values; both are also attributes of MyArray. So, as MyIterator should use MyArray attributes, how should MyIterator be implemented? Perhaps I can send the current object in the initialization:
it=new myIterator(this);
But I guess it's not the best soultion. Or maybe MyArray itself should implement Iterator interface? How is this solved?
EDIT:
Ok, thanks to everybody. This was a simple example of what I wnat to do, so don't care about fixed length array. Waht I really want to do is a circular FIFO, that's why start and end are the cursors.
This circular FIFO will be an array of pairs of ints with, e.g., size 300: int[][] arr=new int[300][2].
When iterating a circular array I have to take care if the counter arrives to the end and make it start from the beginning, so this is how I have solved it:
if (this.start >= this.end ) temp_end=this.end+this.buff.length;
else temp_end=this.end;
int ii;
int j=0;
int[] value=new int[2];
for(int i=this.start; i<temp_end; i++){
ii=i% this.arr.length;
value=this.buff[ii];
//do anything with value
}
But I would like to avoid worrying about these things and just iterate in a simple way, I can do this with iterator interface, but then I have 2 problems: the first one I already explained and has been solved by many answers, and the second one is that my array is made of pairs of ints, and I can't use iterator with primitive types.
Its very unusual to maintain an iterator as an instance variable of the class. You can only traverse the array once - probably not what you want. More likely, you want your class to provide an iterator to anyone that wants to traverse your array. A more traditional iterator is below.
Java 5+ code - I haven't tried to compile or run, so it may be contain errors (not near a dev machine right now). It also uses autobox'ing for converting Integer to int.
public class MyArray implements Iterable<Integer> {
public static class MyIterator implements Iterator<Integer> {
private final MyArray myArray;
private int current;
MyIterator(MyArray myArray) {
this.myArray = myArray;
this.current = myArray.start;
}
#Override
public boolean hasNext() {
return current < myArray.end;
}
#Override
public Integer next() {
if (! hasNext()) throw new NoSuchElementException();
return myArray.arr[current++];
}
#Override
public void remove() {
// Choose exception or implementation:
throw new OperationNotSupportedException();
// or
//// if (! hasNext()) throw new NoSuchElementException();
//// if (currrent + 1 < myArray.end) {
//// System.arraycopy(myArray.arr, current+1, myArray.arr, current, myArray.end - current-1);
//// }
//// myArray.end--;
}
}
....
// Most of the rest of MyArray is the same except adding a new iterator method ....
public Iterator<Integer> iterator() {
return new MyIterator();
}
// The rest of MyArray is the same ....
}
Also note: be careful of not hitting that 500 element limit on your static array. Consider using the ArrayList class instead if you can.
In my opinion it is better to implement MyArray as common Iterable object, so it can be used in a for statement.
My suggestion:
/**
* My array
*/
public class MyArray<TItem> implements Iterable<TItem>
{
/**
* Internal used iterator.
*/
private class MyArrayIterator<TItem> implements Iterator<TItem>
{
private MyArray<TItem> _array;
/**
* #param array The underlying array.
*/
public MyArrayIterator(MyArray<TItem> array)
{
this._array = array;
}
/**
* Gets the underlying array.
*
* #return The underlying array.
*/
public MyArray<TItem> getArray() {
return this._array;
}
#Override
public boolean hasNext() {
// TODO Auto-generated method stub
return false;
}
#Override
public TItem next() {
// TODO Auto-generated method stub
return null;
}
#Override
public void remove() {
// TODO Auto-generated method stub
}
}
public void add(int el){
// do add
}
public void delete(){
// do delete
}
#Override
public Iterator<TItem> iterator() {
// TODO Auto-generated method stub
return new MyArrayIterator<TItem>(this);
}
}
As I said you can use it in a for statement:
private static void test(MyArray<String> strArray)
{
for (String str: strArray) {
// do something
}
}
Iterator is an interface . Iterator<E> which means only Object can go here (E) .
Iterator<Integer> is legal but Integer<int> is not because int is primitive data type
You can change the array to the ArrayList and then iterate over this arraylist. I added getIterator() method that returns the arraylist.iterator() and test it in main() method
import java.util.ArrayList;
import java.util.Iterator;
public class MyArray {
int start;
int end;
ArrayList<Integer> arr;
public MyArray() {
this.start = 0;
this.end = 0;
arr = new ArrayList<Integer>(500);
}
public void add(int el) {
arr.add(el);
this.end++;
}
public void delete() {
arr.remove(arr.size()-1);
this.start++;
}
public Iterator<Integer> getIterator(){
return arr.iterator();
}
public static void main(String[] args) {
MyArray m = new MyArray();
m.add(3);
m.add(299);
m.add(19);
m.add(27);
Iterator<Integer> it = m.getIterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
My suggestion is to let MyArray implement the interface java.lang.Iterable and create an instance of an iterator per iterator() call (as an anonymous class). Then you can use an instance of MyArray directly in a foreach construct:
public class MyArray implements Iterable {
// ...
// Only arr is needed now as an instance variable.
// int start;
// int end;
int[] arr;
// myIterator it;
/**
* From interface Iterable.
*/
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
// The next array position to return
int pos = 0;
public boolean hasNext() {
return pos < arr.length;
}
public Integer next() {
if(hasNext())
return arr[pos++];
else
throw new NoSuchElementException();
}
public void remove() {
throw new UnsupportedOperationException();
}
}
}
}
Update: According to BertF's comment I updated my code to make it clear, that the only instance variable for class MyArray is now arr. The state for the iterator is now inside the anonymous Iterator implementation. So you can create multiple iterator instances which don't interfere each other.
EDIT: this does not work for arrays of primitive types:
you could use Arrays for this:
it = new Arrays.asList(arr).subList(start, end).iterator();
END OF EDIT
If you really want to implement your own iterator, I would suggest an internal class in this scenario. This way you can access MyArray.this from myIterator.
public class MyArray {
....
private class myIterator implements Iterator{
....
}
}
MyArray should implement the Iterator as it is also responsible for maintaining the array. Simple encapsulation principle.

Categories