I'm programming an RPG, and I've come across having to have User-Defined objects in my constructors, and..?

I have no idea how to incorporate them...Here is an example.

This is a "Weapon" constructor:

public Item(String n, int p)


name = n;

price = p;


public Player(String n, int l, int h, int mH, int s, int d, int sp, int e, int g, int m, int mM, int tNL, ArrayList<Item> i)



magic = m;

maxMagic = mM;

toNextLevel = tNL;

inventory = i;


and this is the new "Player" I want to make:

Player plr = new Player("blah",1,1,1,1,1,1,1,1,1,1,1,????????<- ArrayList<Item>

How would I manage that? I can't seem to find a way to do it. I would be VERY thankful if this could be figured out...


I don't know how to pass in an ArrayList, or a User-Defined Object into a method OR a constructor.

2 Answers

  • 1 decade ago
    Favorite Answer

    you could first create a new ArrayList<Item> object, populate it with Items, and then make the Player object using that ArrayList:

    ArrayList<Item> items = new ArrayList<Item>();

    items.add(new Item("Sword", 1000));

    items.add(new Item("Shield", 1000));


    Player plr = new Player("blah",1,1,1,1,1,1,1,1,1,1,1, items);

    • Login to reply the answers
  • Silent
    Lv 7
    1 decade ago

    I'm not really sure what you're asking. Are you saying you don't know how to pass an ArrayList as a parameter to a method? Or that you don't know how to create a new ArrayList object?


    First off, there isn't really such a thing as a "user-defined object" in Java. There's just objects. There's no meaningful distinction between a class you wrote yourself and a class that's a built-in part of the language.

    A constructor is a method; there is no difference between them as far as how parameters are passed.

    You don't seem to have any problem passing Strings and ints as arguments to a method, so I'm not really sure what your difficulty is with ArrayLists. Create a new ArrayList object like so:

    ArrayList<Item> items = new ArrayList<Item>();

    and then pass items as a parameter to the method. Is this what you didn't know how to do? Create an ArrayList?

    • Login to reply the answers
Still have questions? Get your answers by asking now.