Janis Bols
Janis Bols

Reputation: 13

Passing ArrayList reference to another class

I understood that Objects are passed as references in Java. So, Is it correct to do like this? ArrayList is created in parent procedure, then passed to procedure in another class for creating new set of elements in it.

class DO_Thing {
 private static ArrayList<ElementClass> fr = new ArrayList<>();

 public static void do_main() {
    fr= Functions.add_elements(fr);
 }
}

public class Functions {
     public static ArrayList<ElementClass> add_elements(ArrayList<ElementClass > frk) {
        ElementClass ier;
        ResultSet zuzis;
        frk.clear();
        zuzis = dbini.db_getallrow("frakcijas");
        try {
            while (zuzis.next()) {
                ier = new Frakcijas();
                ier.frid = zuzis.getInt("frakcijas_id");
                ier.frnos = zuzis.getString("nosaukums");
                frk.add(ier);
            }
        } catch (SQLException a) {
            System.out.println(a);
        }
        return frk;
    }
}

Upvotes: 1

Views: 1381

Answers (2)

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

  1. Objects are not passed as references, but passed is the value of the reference.
  2. Your code will work, but there is no need to pass the empty ArrayList, when invoking the ielikt_frakcijas() method, since you only clear it.

What you can do :

public static ArrayList<Frakcijas> ielikt_frakcijas() {
   Frakcijas ier;
   ResultSet zuzis;
   ArrayList<Frakcijas> result = new ArrayList<Frakcijas>();
   zuzis = dbini.db_getallrow("frakcijas");
   try {
       while (zuzis.next()) {
           ier = new Frakcijas();
           ier.frid = zuzis.getInt("frakcijas_id");
           ier.frnos = zuzis.getString("nosaukums");
           result.add(ier);
       }
   } catch (SQLException a) {
       System.out.println(a);
   }
   return result;
}

and invoke it like:

frakcijas = Funkcijas.ielikt_frakcijas();

Upvotes: 1

Tetsujin no Oni
Tetsujin no Oni

Reputation: 7367

Functionally, yes. This is a variation on the Builder object construction pattern.

Upvotes: 2

Related Questions