Java methods of calling an object located in an ArrayList

I have a Kostka class that has its own values ​​for width (w), height (h), x and y for drawing it later using 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 to ArrayList .. then call the maluj(g) method for each of the Kostka objects stored in ArrayList


So far I have managed to create a method that stores Kostka objects in an ArrayList , but I don’t 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); } } 
0
source share
2 answers

Method call

This was done in the usual way:

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

However, the way you retrieve kostka from your list will depend on how you declared the list.

Using 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 best way)

 ArrayList<Kostka> kos = new ArrayList<Kostka>(5); Kostka kostka = kos.get(index); 
+3
source

You can roll to retrieve Kostka elements in an 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 that supports Generics, no throw is needed. 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); } 
+2
source

Source: https://habr.com/ru/post/1498885/


All Articles