简体   繁体   中英

How can I dynamically create objects of a class in Java?

Currently I have a project that can statically create objects of a class:

Song song1 = new Song();
song1.setTitle("Paint it Black");
song1.setRating(4);
song1.setPrice(0.99);
Song song2 = new Song("Hey Jude",4.99);
song2.setRating(10);

This works just fine, but I would like to make it so that i can create objects without having to hard code each and every object into my program, because as you can imagine it can get lengthy. Is there a way I can achieve this?

Essentially, instead of

Song song1 = new Song();
Song song2 = new Song();
Song song3 = new Song();
Song song4 = new Song();
Song song5 = new Song();
...
Song songN = new Song();

Have a single algorithm to create my objects (song1, song2, song3, ... songN) for me based on user input

lets say u get the information from some text box. then your code would look like this:

// create only once
List<Song> songs = new ArrayList<>();
//at add song button click
Song song = new Song();
song.setTitle(titleTextBox.getText());
song.setRating(ratingTextBox.getText());
song.setPrice(priceTextBox.getText());
songs.add(song);
// add the toString() method to the Song class
// print the list to see the elements of the list
System.out.println(songs);

Try using a simple array combined with a for loop to create a size of your chosing

Song song[(number of songs)];
for(x=0;x<=(number of songs);x++)
{
    song[x] = new Song();
}

To access your song you would do

song[(song number)].setTitle();

First of all you might want to have an alternate constructor inside your Song class...

private String name;
private int rating;
private double price;

public Song( String name, int rating, double price )
{
    setName(name);
    setRating(rating);
    setPrice(price);
}

// setters/getters

Seems like you're wanting something like this...

  1. Store user input using a list – check out the docs for java.util.Collections
  2. Use a loop to instantiate Song objects – also storing them in a list.
  3. Use the List

Your loop might look a little like this...

List<String[]> userInput = new ArrayList<>();
// Fill list with user input
List<Song> songList = new ArrayList<>();

for( String[] tokens : userInput )
{
    String name = tokens[0];
    int rating = Integer.parseInt(tokens[1]);
    double price = Double.parseDouble(tokens[2]);

    songList.add( new Song(name, rating, price) );
}

// Do something with songList

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM