Jump to content

Regarding Java ArrayList program


Recommended Posts

Hello all, I am new here and i am learning java from the scratch. I was writing a java code about replace the second element of a ArrayList with the specified element. Here is my Code:

 

import java.util.ArrayList;
  public class program {
    public static void main(String[] args){
  ArrayList<String>  color = new ArrayList<String>();

  color.add("Red");
  color.add("Green");

  System.out.println("Original array list: " + color);
  String color = "White";
  color.set(1,new_color);

  int num=color.size();
  System.out.println("Replace second element with 'color'."); 
  for(int i=0;i<num;i++)
  System.out.println(color.get(i));
  }
}

 While run the code it shows an error. i am not understand how to resolve this, can any one please help me on this, I was taking reference from here

Link to comment
Share on other sites

  • 4 weeks later...

Yes, there are a few errors in the code. Here are the issues I found:

  1. The variable new_color is not defined. It seems like you meant to use the variable color instead of new_color when calling the set method on the color ArrayList.
  2. The variable color is already defined as an ArrayList of Strings. You cannot redefine it as a String on the line String color = "White";.
  3. The set method of an ArrayList takes two arguments: the index of the element to replace and the new element. In this case, you should replace color.set(1,new_color); with color.set(1, color);.

Here is the corrected version of the code:

import java.util.ArrayList;
public class program {
  public static void main(String[] args){
    ArrayList<String> color = new ArrayList<String>();

    color.add("Red");
    color.add("Green");

    System.out.println("Original array list: " + color);
    String newColor = "White";
    color.set(1,newColor);

    int num=color.size();
    System.out.println("Replace second element with 'White'."); 
    for(int i=0;i<num;i++)
      System.out.println(color.get(i));
  }
}
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue. Privacy Policy