-1

I have some values (:a , :a , :b , :c , :f , :f) which I want to store in a unique index based Data structure, which I can later iterate over to get my values.

Can any one please let me know which is the simplest way ?

E.g

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

LATER,

Iterate on the DATA STRUCTURE based upon, the INDEX, to get my values

Thanks in advance

Noman K
  • 277
  • 1
  • 5
  • 15

2 Answers2

1

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
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

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.

Murillo Ferreira
  • 1,423
  • 1
  • 16
  • 31