在ArrayList中选择特定值

时间:2015-04-08 00:21:37

标签: java arraylist

我有这个ArrayList,

-----------------------------------------
| c1 | c2 | c3 | c4 | c5 | c6 | c7 | c8 |
-----------------------------------------
| 0  | 1  | 2  | 3  | 0  | 1  | 2  | 3  |
-----------------------------------------

如果用户传递字符串"c5",则 它将获得3个兄弟姐妹及其自身,c5,c6,c7,c8

如果用户传递字符串"c7",则 它将获得3个兄弟姐妹及其自身,c5,c6,c7,c8

如果用户传递字符串"c3",则 它将获得3个兄弟姐妹及其自身,c1,c2,c3,c4

如果用户传递字符串"c1",则 它将获得3个兄弟姐妹及其自身,c1,c2,c3,c4

就像我将ArrayList除以每组中的4个值。

如何只使用1 ArrayList

2 个答案:

答案 0 :(得分:0)

通过索引例如" c5"通过

index = Integer.parseInt("c5".charAt(1)) - 1

之后尝试类似:

for(i = (index/4)*4;i <= (index/4)*4;i++)
    print(array[i]);

答案 1 :(得分:0)

我能用这个产生你的结果:

public static class KeyValuePair {
    public String Key;
    public int Value;

    public KeyValuePair(String key, int value) {
        Key = key;
        Value = value;
    }
}

public static void main(String args[]) {
    List<KeyValuePair> myList;
    myList = new ArrayList<>();
    myList.add(new KeyValuePair("c1", 0));
    myList.add(new KeyValuePair("c2", 1));
    myList.add(new KeyValuePair("c3", 2));
    myList.add(new KeyValuePair("c4", 3));
    myList.add(new KeyValuePair("c5", 0));
    myList.add(new KeyValuePair("c6", 1));
    myList.add(new KeyValuePair("c7", 2));
    myList.add(new KeyValuePair("c8", 3));
    myList.add(new KeyValuePair("c9", 0));
    myList.add(new KeyValuePair("c10", 1));
    myList.add(new KeyValuePair("c11", 2));
    myList.add(new KeyValuePair("c12", 3));

    int indexLocation = -1;
    String keyToFind = "c3";
    for (int i = 0; i < myList.size(); i++) {
        if (myList.get(i).Key.contentEquals(keyToFind)) {
            indexLocation = i;
            break;
        }
    }

    if (indexLocation != -1) {    
        int lowerBound = indexLocation / 4 * 4;
        int upperBound = lowerBound + 4;

        for (int i = lowerBound; i < upperBound; i++) {
            System.out.println(myList.get(i).Key);
        }
    }
}

c3产生了以下结果:

c1
c2
c3
c4
c11产生了以下结果:

c9
c10
c11
c12