0

so I'm writing a registration system app for a university (writing it in JAVA) I have three classes Student, Faculty and Course. In the driver class, I have three ArrayLists of each type to hold different objects of said types. I need an option to print out the current elements in the list and as it is now I basically have the same code written three times for each type of list. I was wondering how would I would implement a function to do this for all three lists. My main question is how would I set up the parameters of the function so that it could print out any type of ArrayList.

One possible solution that I thought of was to make the ArrayLists static and just have the function take in an int as parameter to indicate what type of list is being displayed. I'm not sure if it would be a good idea to make the lists static though.

or am I just overthinking this and I should just leave it as is. my main method is getting pretty long though so I was trying to figure out how to simplify with other methods.

Juan Battini
  • 115
  • 3
  • 14

3 Answers3

0

You should override the toString() method in each of your 3 classes.

Then in your method you would simply loop over each object and call the toString whatever is the type.

See this thread for more information on how to override the method if you don't already know how.

Community
  • 1
  • 1
Jean-François Savard
  • 20,626
  • 7
  • 49
  • 76
0

all my toString methods are indeed Overriden but what I'm trying to ask is how would I implement a function to any type of list as a parameter, in another words

public void showList(List<Object> a) {
     for (int i = 0; i < a.size(); i++) {
         JOptionPane.showMessageDialog(null,a.get(i).toString());
     }
}

and when I call the function I could specify what type of list it is as the parameter, and enter

List<Student> students = new ArrayList<Student>();

showList(students);

However I do realize that this is not possible, but is there a way around it?

Juan Battini
  • 115
  • 3
  • 14
  • You can not add a JOptionPane in your circulation. Because when the size is very heavy, your app will be broken. – MageXellos Feb 08 '15 at 04:26
0

If you stiil want use your showList, may you can modify it like this:

public void showList(List<Object> a) {
     StringBuffer msg = new StringBuffer();
     for (int i = 0; i < a.size(); i++) {
         // generate a sequence
         msg.append(a.get(i).toString() + ",");
     }
     // cut the last comma
     msg = msg.substring(0,msg.length()-1);
     JOptionPane.showMessageDialog(null,msg.toString());
}

I suggest you to create a base class for your three classes and the base class contains an attribute(Name) and two methods(setName,getName). So you can define your list like List, you don't need to care about whether the real entity is Student, Course and so on. You just call getName like: entity.getName() to get the String Value for your list.

MageXellos
  • 154
  • 1
  • 9