Java - calling methods of an object that is in ArrayList

我是研究僧i 提交于 2019-12-25 05:32:19

问题


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

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


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

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);
    }
}

回答1:


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.

Using the Good Ol' Way (Pre-Java 1.5 Style)

// 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);



回答2:


You can perform a "cast" in order to retrieve the Kostka elements of the ArrayList:

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. 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);
}


来源:https://stackoverflow.com/questions/17067728/java-calling-methods-of-an-object-that-is-in-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!