基于索引的Java数据结构

时间:2014-07-07 04:04:49

标签: java data-structures

我有一些值(:a,:a,:b,:c,:f,:f)我想要存储在一个独特的基于索引的数据结构中,我可以稍后迭代以获取我的值。

任何人都可以告诉我哪种方法最简单?

E.g

  1. :一个
  2. :一个
  3. :乙
  4. :C
  5. :F
  6. :F
  7. 后,

    根据INDEX迭代DATA STRUCTURE以获取我的值

    提前致谢

2 个答案:

答案 0 :(得分:1)

如果我理解您的问题,您可以使用List<String>之类的

public static void main(String[] args) {
  List<String> al = Arrays.asList(":a", ":a", ":b",
      ":c", ":f", ":f");
  for (int i = 0; i < al.size(); i++) {
    System.out.printf("%d. %s%n", 1 + i, al.get(i));
  }
}

输出是(注意:索引从0开始,所以我在上面添加了一个以获得您请求的输出)

1. :a
2. :a
3. :b
4. :c
5. :f
6. :f

答案 1 :(得分:1)

您可以使用array,数组是一个可以拥有大量值的对象,您可以使用索引进行访问。

示例:

int a = 10;
int b = 11;
int c = 12;
int d = 13;

int value[] = { a, b, c, d };


//syntax access is value[elementPosition], you have 4 elements inside, positions begins on zero, so you must use 0, 1, 2 and 3 (total of 4).

//value[0] will result 10
//value[1] will result 11
//value[2] will result 12
//value[3] will result 13

你可以使用:

int value[] = { 10, 11, 12, 13 };
int[] value = { 10, 11, 12, 13 };

或者您可以创建一个数组并稍后传递它:

int[] value = new int[4] // 4 = num of values will be passed to this array

value[0] = 10;
value[1] = 11;
value[2] = 12;
value[3] = 13;

value[4] = 14 // this will result IndexOutOfBoundsException, because it will be the 5th element.

您可以对String,float等执行相同的操作。