【发布时间】:2016-09-04 13:55:43
【问题描述】:
我遇到了嵌套 java 类的问题,它看到了外部类对象,但不知何故无法修改它。我读了很多类似的问题,但找不到这个问题的解决方案。这可能是非常简单的事情,但我还不够好,无法弄清楚。 我有 Sorter 类在后台进行一些计算,我决定使用 AsyncTask 在 UI 线程之外执行这些计算。 我的课是这样的
public class Sorter
{
private static List<Long> workingList;
private static int _numberOfContainers, _containerSize, _timesToRepeat;
private static Long _numbersFrom, _numbersTo, _sortingAlgorithmId;
public Sorter(int numberOfContainers, int containerSize, Long numbersFrom, Long numbersTo,
int timesToRepeat, Long sortingAlgorithmId)
{
_numberOfContainers = numberOfContainers;
_containerSize = containerSize;
_numbersFrom = numbersFrom;
_numbersTo = numbersTo;
_timesToRepeat = timesToRepeat;
_sortingAlgorithmId = sortingAlgorithmId;
// perform calculations in the background
new BackgroundCalculations().execute();
}
static class BackgroundCalculations extends AsyncTask<Void,Void,Void>
{
@Override
protected Void doInBackground(Void... voids)
{
workingList = new ArrayList<>(_containerSize);
// workingList is still null after this
_numbersTo += 1; // to fix exclusive number range to inclusive
Random rand = new Random();
for (int i = 0; i < _containerSize; i++)
{
workingList.add((long) (rand.nextDouble() * (_numbersTo - _numbersFrom)) + _numbersFrom))
}
// some calc
return null;
}
}
}
我尝试在 Sorter 构造函数中实例化 workingList,但嵌套类无论如何都无法将项目添加到 workingList。有什么解决办法吗?也许更好的方法来实现没有此类问题的后台计算?
【问题讨论】:
-
你需要重写 AsyncTask 的 onpostExecute 方法,并将结果以 arraylist 的形式从 doInBackground 方法传递,然后在 onPostExecute 方法中使用该数组列表来实例化 workingList。
-
提示:阅读 Java 编码风格指南。 “_”在变量名中没有位置(除非是 CONSTANTS_USING_MULTIPLE_WORDS)
-
@dex 我试图这样做,但我需要访问外部类 workingList 因为一些计算是通过外部类方法进行的。我应该将所有计算移到 AsyncTask 类吗?
-
是的,您可以在后台移动所有计算,因为@GhostCat 请遵循 java 编码准则范例。
-
好的,我完全重新安排了我的 Sorter 类,所以 AsyncTask 是外部的,也是唯一的类。现在一切都变得更加清晰和有效。但是我还是不明白为什么嵌套类不能修改外部类字段。感谢您的帮助,我很高兴能够学习新东西:)
标签: java android class android-asynctask inner-classes