简体   繁体   中英

Can I put a String in an Arraylist when a object is created?

I want to make a program where you can name a String("weapon" for example)and then add that String to a ArrayList. But without typing it yourself like:

MyArrayList.add(Egg); //for example

So that the new Object automatically add to the Arraylist.

So what I did, I created an Arraylist that will hold the weapon names. I made a method, where you can "make" in the main class a object with the weapon name.But how do i make something that when a object (in the main class)is created, it automatically add it self to the arraylist.

(Sorry for bad explaining, I'm from The Netherlands so... If it's a bad explaining please tell me so i can improve it)

Based on my interpretation of your problem, you want to have the user create a weapon name and add it to the ArrayList without having to manually add the code to add it?

A basic way to get String input from a user:

Scanner inputscan = new Scanner(System.in); //reads input from command line
String weapon = inputscan.nextLine(); //waits for user input
MyList.add(weapon);

That way, every time you call the "make" method with that code in it, it will prompt the user to type a weapon name, then the weapon name gets stored in the array.

Maybe I completely misunderstand it, but do you want to do something like this?

private ArrayList<YourObject> list;

public YourMainClass(){
    list = new ArrayList<YourObject>();
}

public void onAdd(String weaponName){
    list.add(new YourObject("weaponName")); // <- this being your issue
}

With YourObject being something like:

public class YourObject
{
    private String name;

    public YourObject(String n){
        setName(n);
    }

    public void setName(String n){
        // Perhaps an if-else to check if n isn't null, nor emtpy?
        name = n;
    }
    public String getName(){
        return name;
    }
}

I think you want to initialize the List with an object in it:

Try using an instance block, like this:

List<String> list = new ArrayList<String>() {{
  add("Egg");
}};

Add the command to add the object to the collection in the constructor.( But this ill advise)

You can create an auxiliary class that will create that object and label to the collection.

class  WeaponFactory
{
  Collection c;
  public WeaponFactory(Collection coll){c=coll;}
  public Weapon makeWeapon(String text)   // Makes sense when the object is not String , like a Weapon class which also contains stats or something
  {
   Weapon w = new Weapon(text)
   c.add(w);
   return w;
  }
}


class Weapon
{
  String name;
  public Weapon(String text)
  {
    name = text;
  }
}

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