Index based Data structure in Java

This question already has an answer here:

  • When to use LinkedList over ArrayList? 28 answers

  • If I understand your question, you could use a List<String> like so

    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));
      }
    }
    

    Output is (note: the index starts at 0, so I added one above to get your requested output)

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

    You could use array , arrays is an object that can have a lot of values, that you access with a index.

    Example:

    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
    

    You could just use:

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

    Or you can create an array and pass it values later:

    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.
    

    You can do the same for String, float, etc.

    链接地址: http://www.djcxy.com/p/19974.html

    上一篇: ArrayList vs LinkedList Java

    下一篇: Java中基于索引的数据结构