简体   繁体   中英

ArrayList inside a method/constructor - Java

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

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.
);

If you are using Eclipse Collections , you can use the FastList implementation to create a list. FastList implements java.util.List as well as richer Eclipse Collections specific types. It can be used as a drop in replacement for ArrayList , if you don't mind it not supporting modCount. Your code would look as follows using FastList .

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

Note: I am a committer for Eclipse Collections

You need to call add on arraylist to add elements.

ArrayList doesn't have constructor with custom object.

Example:

new ArrayList<NPC>().add( new NPC("Player", "All", 0));

EDIT: If chaining of add is the requirement, then Arrays.asList(..) need to be used.

Try this:

new ArrayList<NPC>(Arrays.asList(new NPC[] { new NPC("Rat", "None", 0), new NPC("Dog", "None", 0)})) 

--> creates an Array of NPC's and makes a list out of it

The stuff you tried can be done for arrays of data, but not for ArrayList

This works:

new NPC[] {new NPC(...)};

This doesn't:

new ArrayList<NPC>() {new NPC(...)};

Aside from Arrays.asList() you can also use double brace initialization :

ArrayList<NPC> list = new ArrayList<NPC>() {{
    add(new NPC("Rat", "None", 0));
    add(new NPC("Dog", "None", 0));
}};

Couple of things style + flexibility:

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

should be:

public WeaponsData(Collection<NPC> drops, Collection<NBC> buys, Collection<NPC> sells)  {}  

To populate the Collection use

 Collection.add(element);  

If you want to use the syntax of { foo,bar,baz} use an array. Like so:

NPC[] npcs = new NPC[] {foo,bar,bax};  

you can then do Arrays.asList(npcs) to bring it back into a List

Inline initializers like that are not supported in Java by default. Java has something that "looks" similar, but it's not exactly the same.

Here is how you can define an ArrayList inline (using a technique called "double brace initialisation"):

ArrayList<NPC> npcs = new ArrayList<NPC>()
{ {
   add(new NPC());
   add(new NPC());
}};

As you can see, not very nice. You're also actually creating an instance of a subclass of the ArrayList instead of an ArrayList class.

In Java it is customary to just use the List<T> type to define you variables, so you can use any List implementation.

Consider this instead:

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

Then you can do:

public static WeaponsData AngelicAxe = new WeaponsData(
  Arrays.asList( new NPC("Rat", "None", 0), new NPC("Dog", "None", 0) ),
  Arrays.asList( new NPC("Player", "All", 0) ),
  Arrays.asList( new NPC("Cain", "First", 5000) ) );

There is also a Google Guava set of libraries that has a very nice collections library with lots of helper methods that aid in collection creation and manipulation:

Check it out: http://code.google.com/p/guava-libraries/ and the User Guide

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