简体   繁体   中英

How to iterate a class in ArrayList?

import java.util.*;
class Animal{
String dog; String cat;
}
public class Arraylist {
 public static void main (String[] args) {

     Animal var=new Animal();
     var.dog="german";
     var.cat="persian";

     List <Animal> al=new ArrayList<Animal>();
     al.add(var);

     Iterator itr= al.listIterator();
     while(itr.hasNext())
     {System.out.print(", "+ itr.next());}
   }
}

now i would like to iterate the elements of the class. How could I do that? Thanks!

You are iterating over the elements of your class.

I see some potential issues though :

  1. Rename your class from Arraylist to something else, less similar to java.util.ArrayList .

  2. Change Iterator itr=... to Iterator<Animal> itr=...

  3. If your Animal class doesn't override toString , it should. Otherwise System.out.print(", "+ itr.next()) won't print meaningful output.

Regarding the 3rd point. Add to your Animal class (and potentially to the sub-classes of this class, depending on what you wish to print) :

@Override
public String toString ()
{
    return "someStringThatRepresentsTheStateOfYourAnimalObject";
}

I know your issue is solved, but I would like to kindly propose a solution and some advice so that you can write better Java code.

First of all, the name Arraylist is bad. It may lead to misconception due to the built in Java.Util ArrayList class, and most importantly it does not describe its role! Do you intend to use this as a container for Animal objects? Then you could name this class AnimalList. Are you trying to provide an implementation of the ArrayList (probably more lightweight than then build in java ArrayList) ? Then choose a more generic name describing this list and use generics!

You d better place the Animal class in another source file, but I assume you ve done it like this so that it will be easier to paste here.

Regarding the Iterator part you should implement the Iterable interface (like the java util ArrayList does), and then return an Iterator. You claim that you want to iterate over the elements of the class. But your class has no elements!! You just have a container of animals, whose scope is just in the main method. You should add a container in your class, and add some animals in that Container.

Regarding the toString method, that Animal@2a139a55 you saw was just the memory address of the Animal Object. That's the default operation of toString method when you want to print a class that you have created. If you try to print a class from a java library for Example, you ll see that they have most probably Overrided the toString method to print something more useful.

To sum up, a minimum ArrayList implementation (I kept your name Arraylist) using resizing array coud be:

import java.util.Iterator;
import java.util.NoSuchElementException;

class Animal{
    String dog;
    String cat;

    @Override
    public String toString() {
        return "Dog: " + dog + "\nCat: " + cat + "\n\n";
    }
}


public class Arraylist<Item> {

    public  Item list[];
    private int N = 0;


    public Arraylist() {
        list = (Item[]) new Object[2];
    }

    public boolean isEmpty() {
        return N == 0;
    }

    public int size() {
        return N;
    }

    private void resize(int max) {
        Item[] temp = (Item[]) new Object[max];
        for (int i = 0; i < N; i++) {
            temp[i] = list[i];
        }
        list = temp;
    }

    public void add(Item item) {
        if (N == list.length)
            resize(2 * list.length);
        list[N++] = item;
    }

    public Item remove() {
        if (isEmpty())
            throw new NoSuchElementException();
        Item item = list[N-1];
        list[N-1] = null;
        N--;
        if (N > 0 && N == list.length/4)
            resize(list.length/2);
        return item;
    }



    public Iterator<Item> iterator() {
        return new ArraylistIterator();
    }


    private class ArraylistIterator implements Iterator<Item> {

        private int current = 0;

        private ArraylistIterator() {
            current = 0;
        }

        @Override
        public boolean hasNext() {
            return (current != N);
        }

        @Override
        public Item next() {
            if (hasNext())
                return list[current++];
            throw new NoSuchElementException();
        }

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


    public static void main (String[] args) {

        Animal var=new Animal();
        Animal var2=new Animal();
        Animal var3=new Animal();
        Animal var4=new Animal();

        var.dog="german";
        var.cat="persian";
        var2.dog="german1";
        var2.cat="persian1";
        var3.dog="german2";
        var3.cat="persian2";
        var4.dog="german3";
        var4.cat="persian3";

        Arraylist al = new Arraylist();

        al.add(var);
        al.add(var2);
        al.add(var3);
        al.add(var4);


        Iterator itr= al.iterator();
        while(itr.hasNext())
        {
            System.out.print(itr.next());
        }
    }
}

Hope it helps!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM