简体   繁体   English

Java-ArrayList中对象的调用方法

[英]Java - calling methods of an object that is in ArrayList

I have a class Kostka , that has its own width (w), height (h), x and y positions for drawing it later on a JPanel using this method 我有一个Kostka类,它具有自己的宽度(w),高度(h),x和y位置,以便以后使用此方法在JPanel上进行绘制

void maluj(Graphics g) {
    g.drawRect(x, y, w, h);
}

Now I need to make more of them and add them in ArrayList .. then call the maluj(g) method for each of the Kostka object stored in the ArrayList 现在,我需要制作更多它们,并将它们添加到ArrayList中。然后为存储在ArrayList中的每个Kostka对象调用maluj(g)方法


So far I've managed to make a method that stores the Kostka objects in ArrayList, but I dont know how to call their methods 到目前为止,我已经设法制作了一种将Kostka对象存储在ArrayList中的方法, 但是我不知道如何调用它们的方法

class MyPanel extends JPanel {
    ArrayList kos = new ArrayList(5);

    void addKostka() {
        kos.add(new Kostka(20,20,20,20));
    }

    public void paintComponent (Graphics g) {
        super.paintComponent(g);
    }
}

Invoking Methods 调用方法

That's done the normal way: 这是正常方式:

// where kostka is an instance of the Kostka type
kostka.whateverMethodYouWant();

However, the way to retrieve the kostka from your list will depend on how you declared the list. 但是,从列表中检索kostka的方式将取决于声明列表的方式。

Using the Good Ol' Way (Pre-Java 1.5 Style) 使用“好方法”(Java 1.5之前的样式)

// where index is the position of the the element you want in the list
Kostka kostka = (Kotska) kos.get(index);

Using Generics (The Better Way) 使用泛型(更好的方法)

ArrayList<Kostka> kos = new ArrayList<Kostka>(5);

Kostka kostka = kos.get(index);

You can perform a "cast" in order to retrieve the Kostka elements of the ArrayList: 您可以执行“ cast”以检索ArrayList的Kostka元素:

for (int i = 0; i < kos.size(); i++) {
    Kostka kostka = (Kotska)kos.get(i);
    kostka.maluj(g);
}

If you are using a version of Java which supports Generics, the cast is unnecessary. 如果使用支持泛型的Java版本,则不需要进行强制转换。 You can do: 你可以做:

ArrayList<Kostka> kos = new ArrayList<Kostka>(5);

for (int i = 0; i < kos.size(); i++) {
    Kostka kostka = kos.get(i);
    kostka.maluj(g);
}

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

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