开发者

set() in ArrayList

I am new to Java, please help me.

My program is

import java.util开发者_StackOverflow.*;
import java.lang.*;
class Test
{
    public static void main(String[] args)
    {
        ArrayList al=new ArrayList();
        al.add("a");
        al.add("b");
        for(int i=1;i<=10;i++)
        {
            al.add(i);
        }
        al.remove("a");
        al.set(1,"c");
        for(int j=3;j<=al.size();j++)
        {
            al.set(j,"z");
        }

        System.out.println(al);
    }
};

in above any mistake........plz help me


a) You need to make the class public to run it:

public class Test
{

b) the last semi-colon is a syntax error No it's not, it's just unnecessary noise.

c) This fails with an IndexOutOfBoundsException:

for(int j = 3; j <= al.size(); j++){
    al.set(j, "z");
}

It needs to be:

for(int j = 3; j < al.size(); j++){
    al.set(j, "z");
}

Explanation: List Indexes are zero-based, so the highest position in a List with n elements is n-1


BTW, the above code can be written in a more elegant way like this:

Collections.fill(al.subList(3, al.size()), "z");

Reference:

  • Collections.fill(List<T>, T)
  • List.subList(from, to)


This code will throw an IndexOutOfBounds exception because of the line:

    for (int j = 3; j <= al.size(); j++) {

to fix it, you need to change it to:

    for (int j = 3; j < al.size(); j++) {

This is because the <= means that your for loop iterates over the end of the list.


List~ and Arrayindices start at 0, not 1. So if you have a list of 3 Elements, they go from index: 0, 1, 2. So you normally iterate from (i = 0; i < list.size (); ++i). Less than, not less/equal.

for (int j=3; j < al.size (); j++)


1.The semicolon in the last line

2.change the code from

for(int j=3;j<=al.size();j++)

to

for(int j=3;j<al.size();j++)

Arraylist are always accessed from from 0th index to less than the size of the array.


I think it is necessary to change also the start index from 3 to 2:

for (int j=2; j < al.size (); j++)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜