1

I have this class has constructor taking a String and a Arraylist as argument;

class Foo{
    String ide;
    ArrayList list;

    public TypeOperator(String ide, ArrayList list){
        this.ide = ide;
        this.list = list;
    }
}

so when I initialise the class like below:

Foo one = new Foo("boo", []);

it gives errors. Well I can do this to make it work:

ArrayList empty = new ArrayList();
Foo one = new Foo("boo", empty);

is there any reason why the first solution won't work? Or is there a way to make some changes to make it work? Thanks

ZHICHU ZHENG
  • 191
  • 1
  • 2
  • 8

3 Answers3

9

To represent an Empty List in Java (an ArrayList is a List), we use java.util.Collections.emptyList().

So you could use something like this:

Foo foo = new Foo("boo", (ArrayList) java.util.Collections.emptyList());

In case you need other ways to create a new list in java, see this answer How to make a new List in Java.

Now you may have mixed up Arrays with ArrayList, resulting in usage of an array like syntax, [], to create an ArrayList. But that too is off mark from the language specifications, and you can read more about how to create arrays from SO here, or as is always better, the standard java docs.

And, not related to your question, but you should always code to an interface.

Community
  • 1
  • 1
Sumiya
  • 277
  • 4
  • 4
1

Your class Foo has a wrong constructor name, the correct should be:

class Foo {
  String ide;
  ArrayList list;

  public Foo(String ide, ArrayList list){
    this.ide = ide;
    this.list = list;
  }
}

Your first solution is wrong because you are not passing an instance of ArrayList to the constructor. In order to create an empty ArrayList, you may use:

Foo one = new Foo("boo", new ArrayList());

You may rewrite the Foo class to use the generic type of List:

class Foo {
  String ide;
  List list;

  public Foo(String ide, List list){
    this.ide = ide;
    this.list = list;
  }
}

... and use the java.util.Collections.EMPTY_LIST to represent empty lists:

Foo one = new Foo("boo", Collections.EMPTY_LIST);
Alexandre V.
  • 360
  • 4
  • 8
0

The TypeOperator function definition expects an argument of type ArrayList. The example is attempting to pass an empty array literal.

The first solution is incorrect because there is a type mismatch between ArrayList and [].

A possible solution would be changing the function definition to

    public TypeOperator(String ide, <some-type>[] list){
        this.ide = ide;
        this.list = new ArrayList(list);
    }

which could be called via

    TypeOperator("somestring", new <some-type> [<some-dimension>]);