0

I am using arraylist in my java program but the problem is that when i add an item in arraylist its adding on the same index so i want to know that how to increment array index in array list.

ArrayList arr = new ArrayList(500);
StringTokenizer st = new StringTokenizer(line, ":Mode set - Out of Service In Service");
while(st.hasMoreTokens()){
    arr.add(st.nextToken());
}

In above code its keep adding item on the same index i.e. arr[0].

2
  • 2
    How do you know it's adding it on index 0 ? Commented Jul 1, 2011 at 9:43
  • 2
    do you want to delimit line by ":Mode set - Out of Service In Service"? Commented Jul 1, 2011 at 9:43

4 Answers 4

1

You can specify at what index the element must be added:

arr.add(index,st.nextToken());
Sign up to request clarification or add additional context in comments.

Comments

1

There's nothing wrong with your code. I don't believe that it would add to position zero.

Prove it by displaying the contents: System.out.println(arr);

Comments

0

Do you really need to initalize the ArrayList size? Try your original code changing

ArrayList arr = new ArrayList(500);

for

ArrayList arr = new ArrayList();

1 Comment

ya i know that there is no need to initialize the arraylist size. I was experimenting something. Thanks for your concern,
0

Your code works fine. I cant see any problem.
How do you know whats the value at index 0, I mean are you debugging it?
Is that text really your delimiter ?

2 Comments

yes that text is my delimiter. It works fine but when i tried to print values of index 0 position the whole string displayed and when i tried to print index 1 value, it shows an error.
thanks for reply. I was doing a silly mistake. Problem Solved finally.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.