List集合排序问题
以下代码,编译通过(android4.0.3),在手机上运行时,报异常:java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableList$1.set(Collections.java:1106)
at java.util.Collections.sort(Collections.java:1896)
at com.example.sensor.MainActivity.onCreate(MainActivity.java:86)
at android.app.Activity.performCreate(Activity.java:4479)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1050)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2041)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2104)
at android.app.ActivityThread.access$600(ActivityThread.java:134)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:4624)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
at dalvik.system.NativeStart.main(Native Method)
代码如下:
//从传感器管理器中获得全部的传感器列表
List <Sensor> allSensors = sm.getSensorList(Sensor.TYPE_ALL);
try{
Comparator<Sensor> comparator = new Comparator<Sensor>(){
public int compare(Sensor arg0, Sensor arg1) {
return arg0.getType()- arg1.getType();
}
};
Collections.sort(allSensors,comparator);
} catch (Exception e)
{
e.printStackTrace();
}
android list exception 手机 --------------------编程问答-------------------- Comparator的compare()方法返回值只能是-1 ,0,1 --------------------编程问答-------------------- 修改了代码,如下,但还是报原来的那些异常: --------------------编程问答-------------------- try{
Comparator<Sensor> comparator = new Comparator<Sensor>(){
public int compare(Sensor arg0, Sensor arg1) {
int a =0;
a = arg0.getType()- arg1.getType();
System.out.println("a = " + a);
if (a > 0)
return 1;
else if (a == 0)
return 0;
else
return -1;
}
};
Collections.sort(allSensors,comparator);
} catch (Exception e)
{
e.printStackTrace();
System.out.println("\n产生了异常! e=" + e);
} --------------------编程问答-------------------- 难道就解决不了吗?
补充:移动开发 , Android