2

I want to override the title of each movie in a list.
I tried to make the x static and final but the compiler complains.

List<Movie> mList = new ArrayList<Movie>();

for(int i = 0; i < 5; i++)
{
int x;
mList.add(new Movie(){


  toString(){

   // need an easy way to give a unique string to each movie here.
   return "Movie" + x;
  } 
}
}
4

1 回答 1

6

这应该有效:

List<Movie> mList = new ArrayList<Movie>();

for (int i = 0 ; i < 5 ; i++) {
    final int x = i;  // or anything else, but you must assign it some value
    mList.add(new Movie() {
        @Override
        public String toString(){
            return "Movie" + x;
        } 
    });
}

您不能制作x static-static修饰符仅用于类的数据字段(或方法)。此外,x确实必须final允许toString匿名类的方法访问它。

于 2012-09-24T02:18:26.697 回答