By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,648 Members | 1,528 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,648 IT Pros & Developers. It's quick & easy.

how to remove first 5 elements in arraylist among ten elements?

P: 1
this question ask interviewer
Expand|Select|Wrap|Line Numbers
  1. for(int i=0;i<=4;i++){
  2. list.remove(list.get(i));
  3. }
this code should not work........

please send any one send to my mail <Moderator Removed Email>
Apr 26 '12 #1
Share this Question
Share on Google+
3 Replies


Rabbit
Expert Mod 10K+
P: 12,421
You say it should work. But obviously it doesn't. It would help to know what it's doing instead of what you intended.

However, if I was to guess, it's because you're changing the index that you're removing. You're forgetting that as you remove each element, all the remaining indexes decrement by 1.
Apr 26 '12 #2

P: 21
You Can simply add the list value of listindex greate than 5 By
for(int i=0;i>=4;i++){
list.add(i);
or
list.add(i.Tostring());
}
Apr 29 '12 #3

P: 4
maybe,you can write the code like this:
Expand|Select|Wrap|Line Numbers
  1. list remList = new ArrayList();
  2. for(int i=0;i<=4;i++){
  3. remList.add(allList.get(i));
  4. }
  5. allList.removeAll(remList);
  6.  
Jun 5 '12 #4

Post your reply

Sign in to post your reply or Sign up for a free account.