문제

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?

도움이 되었습니까?

해결책 2

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");
}

다른 팁

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

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"));
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top