Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList inside a method/constructor - Java

Tags:

java

arraylist

After search around google I couldn't find a answer for that, I'm not too familiar to Java, I use C# most of the time and I know that using C# it is possible to do and probably it is in Java.

Ps: Sorry the Highlight, I don't know how to use that here.

I have a constructor:

public WeaponsData(ArrayList<NPC> _drop, ArrayList<NPC> _buy, ArrayList<NPC> _sell) { }

Then when I try to create the Object creating the ArrayLists() directly on it, it doesn't work:

public static WeaponsData AngelicAxe = new WeaponsData(new ArrayList<NPC>() { new NPC("Rat", "None", 0), new NPC("Dog", "None", 0) },
                new ArrayList<NPC>() { new NPC("Player", "All", 0) },
                new ArrayList<NPC>() { new NPC("Cain", "First", 5000) }
                );

There is no way to do that on Java?

Thank you

like image 827
Kyky Avatar asked Dec 27 '22 18:12

Kyky


1 Answers

ArrayList does not have the constructors necessary to do that. You can either wrap the arguments in a call to Arrays.asList():

public static WeaponsData AngelicAxe = new WeaponsData(
    new ArrayList<NPC>(
       Arrays.asList(
          new NPC("Rat", "None", 0),
          new NPC("Dog", "None", 0)
       )
    ),
// etc
);

or use the factory methods provided by the Guava Framework:

public static WeaponsData AngelicAxe = new WeaponsData(
    Lists.newArrayList(
        new NPC("Rat", "None", 0),
        new NPC("Dog", "None", 0)
    ),
// etc.
);

Of course, if you use Guava, you should probably use an immutable collection instead, as you are apparently trying to implement a constant:

public static final WeaponsData ANGELIC_AXE = new WeaponsData(
    ImmutableList.of(
        new NPC("Rat", "None", 0),
        new NPC("Dog", "None", 0)
    ),
// etc.
);
like image 68
Sean Patrick Floyd Avatar answered Jan 08 '23 09:01

Sean Patrick Floyd