将数组列表转换为稀疏数组

Convert Array list to Sparse Array

我从一个项目中复制了一些代码,想在我的私人应用中重用其中的一小部分。

class 包含一个稀疏数组

public class GolfResult {

    String hcpAfter;
    String hcpBefore;
    SparseArray roundResults;

    public GolfResult() {
        hcpAfter = "";
        hcpBefore = "";
        roundResults = new SparseArray();
    }
}

我为 roundResults 创建了一个 ArrayList,其中填充了必要的数据。

然后我尝试用内容填充实例。

GolfResult golferRes = new GolfResult();
SparseArray<RoundResults> hu= new SparseArray<>();
hu = roundresults; // *
golferRes.setHcpAfter("33");
golferRes.setHcpBefore("kk");
golferRes.setRoundResults(hu);

但问题是hu = roudresults是不可能的,因为错误信息:

required: Android.util.SparseArray found: java.util.Array List

欢迎任何帮助。

在收到两个有用的答案后,我更进一步了,但现在我面临的问题是我的 SparseArray hu 是空的 {}。

hu的内容应该是具有以下结构的class轮结果:

public class RoundResults {
boolean actualRound;
private List<HoleResult> holeResults;
Integer roundId;
Integer roundNumber;
String unfinishedReason;

arrayList roundresults 的大小为 1,并且在对象中有数据。

unfinishedReason =""
holeResults = ArrayLIST size= 18
roundID = "1"
roundNumber = "1"
actualRound = true

胡={}

mValues = All elements are null
mSize = 0

有人知道为什么吗?

如果我很了解你的问题,也许你可以试试这个:

for ( int i=0; i<roundresults.size(); i++ ) {
    hu.put(i,roundresults.get(i));
}

SparseArray 不同于 ArrayList,来自 documentation:

SparseArrays map integers to Objects. Unlike a normal array of Objects, there can be gaps in the indices. It is intended to be more memory efficient than using a HashMap to map Integers to Objects, both because it avoids auto-boxing keys and its data structure doesn't rely on an extra entry object for each mapping.

它使用键值对原则,其中键是整数,键映射是对象的值。您需要使用 put [(int key, E value)](https://developer.android.com/reference/android/util/SparseArray.html#put(int, E)) ,其中 E 是您的对象。请记住:

Adds a mapping from the specified key to the specified value, replacing the previous mapping from the specified key if there was one.

因此您需要使用循环将每个对象添加到 ArrayList 中,如@valentino-s 所说:

SparseArray<RoundResults> hu= new SparseArray<>();
for( int i = 0; i < roundresults.size(); i++) {
  // i as the key for the object.
  hu.put(i, roundresults.get(i));
}

经过反复试验,我找到了空胡的解决方案:

我使用的不是 put,而是 append,它现在可以正常工作了。

hu.append(i, roundresults.get(i));

是时候喝杯啤酒了。