0

I'm trying to add an array of object in my class(MainActivity), for example

public class MainActivity extends Activity {
    private class A {
      A(String s) { ..}
    }
    private static final A[] aList1;
    private static final List<A> aList2;
    ...

both are ok with me.

But I don't know how to initialize aList1 or aList2. Had already tried following:

private static final A[] aList;
static {
    a = new A[2];
    a[0] = new A("emails");
}

And also tried:

private static final List<A> aList = new ArrayList<A>(){{
    add(new A("emails"));
}};

but eclipse are complaining: No enclosing instance of type MainActivity is accessible. Must qualify the allocation with an enclosing instance of type MainActivity (e.g. x.new A() where x is an instance of MainActivity).

How to fix this?

Deqing
  • 14,098
  • 15
  • 84
  • 131

3 Answers3

1

ArrayList is better than List. It has more methods. Sample:

private static final A[] aList2;
private static final ArrayList<A> aList = new ArrayList<A>(); //you can add in static aList=new ArrayList<a>();

....or...
static {
    aList = new ArrayList(a):
    aList.add(new A("emails"));
}

To convert the array to A[]:

A[] array = new A[aList.size()];
array = aList.toArray(array);

To fast gets value:

for (A item : aList) {
    ... do somme with item
}

To gets any item: aList.get(int index);

user2884743
  • 17
  • 1
  • 2
  • 5
0

final fields can only be initialized inline and in the constructor.

private static final A[] aList = new A[2];

After that you can use the static initializer

static {
 aList[0] = new A("emails");
}

or with a list

private static final List<A> aList = new ArrayList<>();

static {
 aList.add(new A("example"));
}
Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
0

I think I understood your problem now. You have a inner class A declared inside your class MainActivity, right? Well, in this case you wont be able to initialize your static final variables since you gonna need an instance of MainActivity to create a new instance of A. What I suggest you to do is to make your class A a static class

private static class A {
    // code here
}

so that you will be able to instantiate as

A a = new MainActivity.A("someString");

and the variables initialization as

private static final A[] aList;

static {
    a = new A[2];
    a[0] = new MainActivity.A("emails");
}
Trein
  • 3,658
  • 27
  • 36
  • The problem solved by declaring my inner class A as `static`. Btw as the `aList` is defined inside `MainActivity` so it is ok to use `A a = new A("emails");` – Deqing Oct 16 '13 at 02:59