-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

3
  • Like a List<String>? Commented Jul 7, 2014 at 4:07
  • Yes But If a unique Index (simple iterating number is STORED seperately), it will be good. Commented Jul 7, 2014 at 4:08
  • Indexes don't need to be stored. That's the whole point. Maybe you mean a map? Commented Jul 7, 2014 at 4:14

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

4 Comments

How can I add the values dynamically in a loop ?
List<String> al = new ArrayList<String>(); for (char i = 'a'; i < 'g'; i++) { al.add(":" + i);}
Hii !! I was wrong. In case the values are same, the reletive key should also be the same 1. :a 1. :a 2. :b 3. :c 4. :f 4. :f
@NomanK That's a very different question. I suggest you post another.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.