0

我使用以下代码将元素从 ArrayList 转换为字符串:

public static List<Location> GPSLocalLocations = new ArrayList<Location>(1);
String mystr = "";
for (int i=0; i<GPSService.GPSLocalLocations.size(); i++)
{
mystr += "\n" + GPSService.GPSLocalLocations.get(i).toString();
}

将我的代码更改为以下内容:

for (int i=0; i<GPSService.GPSLocalLocations.size(); i++)
{
    gpslog.append("\n").append(GPSService.GPSLocalLocations.get(i).toString());
}

它会导致更少的 GC Free 消息:)。我的错误,应用程序并没有因此而挂起......我想是因为我多次运行了我的 ASyncTask ......

但仍然迭代超过 1000 个元素的 ArrayList 需要一些时间 [大约 10 秒]。那样行吗?

4

1 回答 1

0

我建议使用StringBuilder

从这里http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.2_r1.1/android/location/Location.java#Location.toString%28%29

@Override public String  [More ...] toString() {
    return "Location[mProvider=" + mProvider +
        ",mTime=" + mTime +
        ",mLatitude=" + mLatitude +
        ",mLongitude=" + mLongitude +
        ",mHasAltitude=" + mHasAltitude +
        ",mAltitude=" + mAltitude +
        ",mHasSpeed=" + mHasSpeed +
        ",mSpeed=" + mSpeed +
        ",mHasBearing=" + mHasBearing +
        ",mBearing=" + mBearing +
        ",mHasAccuracy=" + mHasAccuracy +
        ",mAccuracy=" + mAccuracy +
        ",mExtras=" + mExtras + "]";
}

我建议您自己按照以下方式编写:

public static List<Location> GPSLocalLocations = new ArrayList<Location>(1);
StringBuilder gpslog = new StringBuilder();
for (int i=0; i<GPSService.GPSLocalLocations.size(); i++)
{
    Location location = GPSService.GPSLocalLocations.get(i); 
    gpslog.append("\n")
        .append("Location[Provider=").append(location.getProvider(())())
        .append(",Time=").append(location.getTime())
        .append(",Latitude=").append(location.getLatitude())
        .append(",Longitude=").append(location.getLongitude())
        .append(",HasAltitude=").append(location.getHasAltitude())
        .append(",Altitude=").append(location.getAltitude())
        .append(",HasSpeed=").append(location.getHasSpeed())
        .append(",Speed=").append(location.getSpeed())
        .append(",HasBearing=").append(location.getHasBearing())
        .append(",Bearing=").append(location.getBearing())
        .append(",HasAccuracy=").append(location.getHasAccuracy())
        .append(",Accuracy=").append(location.getAccuracy())
        .append(",Extras=").append(location.getExtras()).append("]");
}
于 2012-04-13T20:32:18.600 回答