Dynamically creating a new instance in Java

I have a class called CD

with the following private variables:

private String artist = "";
private String year = "";
private String albumName = "";
private ArrayList<String> songs = new ArrayList<String>();

      

This class is used to store input data, which is in this format:

Led Zeppelin
1979 In Through the Outdoor
-In the Evening
-South Bound Saurez
-Fool in the Rain
-Hot Dog
-Carouselambra
-All My Love
-I'm Gonna Crawl

      

I have a class CDParser

that is responsible for parsing a file named sample.db

line by line to store it in our CD

object. After parsing, the object, CD

after initialization with using, CD newCD = new CD()

has the following structure:

artist = "Led Zeppelin"

year = "1979"

albumName = "In Through the Outdoor"

songs = {"-In the Evening", "-South Bound Saurez", "-Fool in the Rain", "-Hot Dog"}

      

Now .. For this project sample.db

contains many albums which look like this:

Led Zeppelin
1979 In Through the Outdoor
-In the Evening
-South Bound Saurez
-Fool in the Rain
-Hot Dog
-Carouselambra
-All My Love
-I'm Gonna Crawl

Led Zeppelin
1969 II
-Whole Lotta Love
-What Is and What Should Never Be
-The Lemon Song
-Thank You
-Heartbreaker
-Living Loving Maid (She Just a Woman)
-Ramble On
-Moby Dick
-Bring It on Home

Bob Dylan
1966 Blonde on Blonde
-Rainy Day Women #12 & 35
-Pledging My Time
-Visions of Johanna
-One of Us Must Know (Sooner or Later)
-I Want You
-Stuck Inside of Mobile with the Memphis Blues Again
-Leopard-Skin Pill-Box Hat
-Just Like a Woman
-Most Likely You Go Your Way (And I'll Go Mine)
-Temporary Like Achilles
-Absolutely Sweet Marie
-4th Time Around
-Obviously 5 Believers
-Sad Eyed Lady of the Lowlands

      

I have so far been able to parse all three different albums and save them to my object CD

, but I came across a roadblock where I just save all three albums to the same object newCD

.

My question: is there any way to initialize the software designer CD

, who will follow the format newCD1

, newCD2

, newCD3

etc., as I can make out sample.db

?

This means that when parsing this file:

  • newCD1

    there will be an album In Through the Outdoor

    (and its corresponding private vars)

  • newCD2

    there will be an album II

    (and its corresponding private vars)

  • newCD3

    there will be an album Blonde on Blonde

    , etc.

Is this a smart way to do it? Or could you suggest me a better way?

EDIT:

Attached code for my parser. ourDB

is ArrayList

containing each line sample.db

:

    CD newCD = new CD();

    int line = 0;

    for(String string : this.ourDB) {
        if(line == ARTIST) {
            newCD.setArtist(string);
            System.out.println(string);
            line++;
        } else if(line == YEAR_AND_ALBUM_NAME){
            String[] elements = string.split(" ");

            String[] albumNameArr = Arrays.copyOfRange(elements, 1, elements.length);

            String year = elements[0];
            String albumName = join(albumNameArr, " ");

            newCD.setYear(year);
            newCD.setAlbumName(albumName);

            System.out.println(year);
            System.out.println(albumName);

            line++;
        } else if(line >= SONGS && !string.equals("")) {
            newCD.setSong(string);
            System.out.println(string);
            line++;
        } else if(string.isEmpty()){
            line = 0;
        }
    }

      

+3


source to share


3 answers


You have a single object CD

, so you rewrite it. You can store a collection CD

s instead . For example:.



List<CD> cds = new ArrayList<>();

CD newCD = new CD();
int line = 0;

for(String string : this.ourDB) {
    if(line == ARTIST) {
        newCD.setArtist(string);
        System.out.println(string);
        line++;
    } else if(line == YEAR_AND_ALBUM_NAME){
        String[] elements = string.split(" ");

        String[] albumNameArr = Arrays.copyOfRange(elements, 1, elements.length);

        String year = elements[0];
        String albumName = join(albumNameArr, " ");

        newCD.setYear(year);
        newCD.setAlbumName(albumName);

        System.out.println(year);
        System.out.println(albumName);

        line++;
    } else if(line >= SONGS && !string.equals("")) {
        newCD.setSong(string);
        System.out.println(string);
        line++;
    } else if(string.isEmpty()){
        // We're starting a new CD!
        // Add the one we have so far to the list, and start afresh
        cds.add(newCD);
        newCD = new CD();
        line = 0;
    }
}

// Take care of the case the file doesn't end with a newline:
if (line != 0) {
    cds.add(newCD);
}

      

+7




The problem is that you are using the same object reference CD

to populate the parse values โ€‹โ€‹of the file.

Just make sure you initialize and save each instance CD newCD

every time you start parsing the contents of a new album.

You can do the following:

List<CD> cdList = new ArrayList<>();
for (<some way to handle you're reading a new album entry from your file>) {
    CD cd = new CD();
    //method below parses the data in the db per album entry
    //an album entry may contain several lines
    parseData(cd, this.ourDB);
    cdList.add(cd);
}
System.out.println(cdList);

      



Your current way of parsing the file works, but doesn't read as readable as it should. I would recommend using two loops:

List<CD> cdList = new ArrayList<>();
Iterator<String> yourDBIterator = this.ourDB.iterator();
//it will force to enter the first time
while (yourDBIterator.hasNext()) {
    //do the parsing here...
    CD cd = new CD();
    //method below parses the data in the db per album entry
    //an album entry may contain several lines
    parseData(cd, yourDBIterator);
    cdList.add(cd);
}

//...
public void parseData(CD cd, Iterator<String> it) {
    String string = it.next();
    int line = ARTIST;
    while (!"".equals(string)) {
        if (line == ARTIST) {
            newCD.setArtist(string);
            System.out.println(string);
            line++;
        } else if(line == YEAR_AND_ALBUM_NAME){
            String[] elements = string.split(" ");
            String[] albumNameArr = Arrays.copyOfRange(elements, 1, elements.length);
            String year = elements[0];
            String albumName = join(albumNameArr, " ");
            newCD.setYear(year);
            newCD.setAlbumName(albumName);
            System.out.println(year);
            System.out.println(albumName);
            line++;
        } else if(line >= SONGS && !string.equals("")) {
            newCD.setSong(string);
            System.out.println(string);
            line++;
        }
        if (it.hasNext()) {
            string = it.next();
        } else {
            string = "";
        }
    }
}

      

Then your code

+5


source


I suggest using the Builder design pattern to create a CD object. If you read the lines always in the same order, it won't be difficult to implement and use. Nice tutorial: http://www.javacodegeeks.com/2013/01/the-builder-pattern-in-practice.html

0


source







All Articles