简体   繁体   English

如何在ArrayList中迭代一个类?

[英]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 . 将您的类从Arraylist重命名为其他类似于java.util.ArrayList

  2. Change Iterator itr=... to Iterator<Animal> itr=... Iterator itr=...更改为Iterator<Animal> itr=...

  3. If your Animal class doesn't override toString , it should. 如果您的Animal类没有覆盖toString ,它应该。 Otherwise System.out.print(", "+ itr.next()) won't print meaningful output. 否则System.out.print(", "+ itr.next())将不会打印有意义的输出。

Regarding the 3rd point. 关于第3点。 Add to your Animal class (and potentially to the sub-classes of this class, depending on what you wish to print) : 添加到您的Animal类(可能还有这个类的子类,具体取决于您要打印的内容):

@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. 我知道你的问题已经解决,但我想提出一个解决方案和一些建议,以便你可以编写更好的Java代码。

First of all, the name Arraylist is bad. 首先, Arraylist这个名字很糟糕。 It may lead to misconception due to the built in Java.Util ArrayList class, and most importantly it does not describe its role! 由于内置的​​Java.Util ArrayList类,它可能会导致误解,最重要的是它没有描述它的作用! Do you intend to use this as a container for Animal objects? 您是否打算将其用作Animal对象的容器? Then you could name this class AnimalList. 然后你可以命名这个类AnimalList。 Are you trying to provide an implementation of the ArrayList (probably more lightweight than then build in java ArrayList) ? 您是否尝试提供ArrayList的实现(可能比在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. 你最好将Animal类放在另一个源文件中,但我认为你已经这样做了,这样就可以更容易地粘贴到这里了。

Regarding the Iterator part you should implement the Iterable interface (like the java util ArrayList does), and then return an Iterator. 关于Iterator部分,你应该实现Iterable接口(就像java util ArrayList那样),然后返回一个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. 您应该在类中添加一个容器,并在该Container中添加一些动物。

Regarding the toString method, that Animal@2a139a55 you saw was just the memory address of the Animal Object. 关于toString方法,您看到的Animal @ 2a139a55只是Animal对象的内存地址。 That's the default operation of toString method when you want to print a class that you have created. 当您要打印已创建的类时,这是toString方法的默认操作。 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. 如果您尝试从示例的java库中打印一个类,您将看到他们最有可能重写了toString方法来打印更有用的东西。

To sum up, a minimum ArrayList implementation (I kept your name Arraylist) using resizing array coud be: 总而言之,使用调整大小数组的最小ArrayList实现(我保留了你的名字Arraylist)可以是:

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!! 希望能帮助到你!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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