In Java: I have a class Students. I would like to read a list of students from a file. Which one is more elegant:

  1. Reading and constructing the list in main(), and creating a Student object with the new list passed to the constructor

  2. Passing a FileReader to the constructor, who does the reading?

  3. Something else?

  • you should concrete more your question. You can get thousands of answers – iberbeu Mar 15 '13 at 15:10
  • 1
    Try to read file in other method. This method can b private and be invoke by other public method. – user1929959 Mar 15 '13 at 15:12
  • @iberbeu Why do you need more information? What I need is just that. – user1377000 Mar 15 '13 at 15:15

Create a dumb object of student.

Create a method to read each line of the file creating a new student object so you end up with a list of students.

Separate the logic of building up the list from determining which bit of the text file holds which attribute of the student object.

Just remember to follow rules like separation of concern and the principles of SOLID.

  • Up-vote just for the SOLID reference! :) – StormBringerX Mar 15 '13 at 15:16

Sounds like the factory pattern is required, something along the lines of a StudentFactorywhich generates the students object.

You should have that as an interface and a FileStudentFactory implementation which does the reading of the file and then if you wanted a different provider later you change out the implementation.



Use a separate method, which does the reading and the initialization of the Student object. The benefit of this is, that you can reuse this wherever you need it, not only in main or while constructing a new Student.

You could also implement the Serializable interface.


Which one is more elegant

Elegance (in programming) is a matter of personal taste. You need to make up your own mind.

Other things to consider are:

  • whether a particular approach provides the required functionality,
  • whether the API is easy to understand, and
  • whether the API supports use-cases other than the current one; i.e. whether it is reusable.

If you create class student you probably need to create a method which returns name of students like this

public String getName(){
return this.name;

and in main class you create Student Object in an array or ArrayList like this:

Student [] students = new Student [size];

and then you have setName(String name) and getName()

Then :

Create DefaultListModel add names to the model then add model to the list like This

DefaultListModel model = new DefaultListModel ();
for(int i = 0; i< students.length; i++){

I didn't test it hope you get the idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy