###一、创建Dialog时 Dialog dialog = new Dialog(getApplicationContext()); 传入getApplicationContext()上下文在运行期间为什么报错?
Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
在这里我们需要先明白3个Context概念:
1、Activity.getApplicationContext():
Return the context of the single, global Application object of the current process. This generally should only be used if you need a Context whose lifecycle is separate from the current context, that is tied to the lifetime of the process rather than the current component.
2、Activity.this/View.getContext():
Returns the context the view is running in, through which it can access the current theme, resources, etc.
3、Activity.getBaseContext():
return the base context as set by the constructor or setBaseContext
Activity.this与getApplicationContext()的生命周期不同, 前者的生命周期依赖于所在的Activity,后者的生命周期依赖于整个应用。所以new Dialog(getApplicationContext())时会发生错误,Dialog依赖的是一个View, 而View对应一个Activity,若传入getApplicationContext(),其生命周期是整个应用,当退出当前Activity的时候,就会报Unable to add window – token null is not for an application的错误,应该传入当前Activity的Context。
###二、二分排序
最近面试时碰到了一个二分排序,由于完全不知道二分排序的思想就GG了;面试结束后就赶紧学习了下二分排序。
####1、算法思想:二分法插入排序是在插入第i个元素时,对前面的0~i-1元素进行折半,先跟他们中间的那个元素比,如果小,则对前半再进行折半,否则对后半进行折半,直到left>right,然后再把第i个元素前1位与目标位置之间的所有元素后移,再把第i个元素放在目标位置上。
####2、分析:
二分排序的时间复杂度是O(n*log2n),空间复杂度O(1),是稳定排序。
####3、实现
####以数组的方式实现:
int[] data = { 34, 32, 12, 61, 23, 36, 40, -15, 21, 11 };
int i, j;
int low, high, mid;
int temp;
for (i = 1; i < data.length; i++) {
temp = data[i];
low = 0;
high = i - 1;
while (low <= high) {
mid = (low + high) / 2;
if (data[mid] > temp)
high = mid - 1;
else
low = mid + 1;
}
for (j = i - 1; j > high; j--)
data[j + 1] = data[j];
data[high + 1] = temp;
}
for (i = 0; i < 10; i++) {
System.out.printf("%d\t", data[i]);
}
####以集合的方式实现:
public class BinarySortDemo {
public static void main(String[] args) {
List<Integer> datas = new ArrayList<Integer>();
for(int i=0; i<10; i++){
datas.add(new Random().nextInt(100));
}
for(Integer data : datas){
System.out.print(" "+data);
}
System.out.println();
sort(datas);
}
public static void sort(List<Integer> datas){
int i;
int low, high, mid;
Integer temp;
for (i = 1; i < datas.size(); i++) {
temp = datas.get(i);
low = 0;
high = i - 1;
while (low <= high) {
mid = (low + high) / 2;
if (datas.get(mid) > temp)
high = mid - 1;
else
low = mid + 1;
}
datas.remove(temp);
datas.add(high + 1, temp);
}
for(Integer data : datas){
System.out.print(" "+data);
}
}
}