【发布时间】:2013-05-14 07:22:48
【问题描述】:
为什么同一段(简单)Java 代码在不同的 Android 设备上的行为会大不相同?
那段简单的代码就是String.replace(CharSequence target, CharSequence replacement)与target == ""的使用:
package com.example.stringreplacetest;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String str = "just_a_string";
System.out.println(str.replace("", "-"));
((TextView) findViewById(R.id.textView)).setText(str.replace("", "-"));
}
}
它在我的 LG Optimus 3D P920 (Android 2.3.3) 和我姐姐的三星 Galaxy S2 (Android 4.1.2) 上产生 -j-u-s-t-_-a-_-s-t-r-i-n-g-,我猜你的大多数设备上也是如此。 em>
但它在我的 LG Optimus Chic (Android 2.2) 上停止(怀疑是无限循环)。
旧的 LG Optimus Chic 和 Android 2.2 可能有问题。 (String.replace() 确实有a bug。)但是String.replace() 中的the piece of code 相对简单——“简单”意味着没有动态绑定、没有线程等......
that piece of code 不应该在编译期间完成吗? Java 编译器是如何工作的(我知道 Java 是一种跨平台语言,它的工作方式可能不同)?
附:为了确保它是同一段编译代码,我实际上通过 USB 将编译后的.apk 传输到我的 Android 手机,而不是使用 Eclipse 直接在设备中运行它们。
我找到了Android 2.2 Froyo的源代码:
它确实在target.length == 0 时会导致无限循环(因为在do-while loop 中,string.indexOf("", tail) 将永远返回-1)。
疑虑已消除。但是……
我仍然不知道为什么在不同的设备上运行时会加载不同版本的String 类。这就是跨平台的意思吗?
【问题讨论】:
-
Android 2.2 中的
String.replace()方法是否会加载一个库(例如正则表达式模式?)会产生这种差异?顺便说一句where can i get the source of Android 2.2?
标签: android compiler-construction java str-replace