Create an ArrayList only containing Strings. Print using enhanced for loop

13,151

Solution 1

You may want to use below methods to insert and remove:

void    add(int index, E element)
 E      remove(int index)

e.g. Mahendra is at index 2(index starts from 0), then to add Harry in front of Mahendra, just do as below:

  names.add(2, "Harry"); //This will push Mahendra at index 3

To remove crrent index 4,

  names.remove(4);

To remove previous index 4, which has become index 5 now,

  names.remove(5);

Solution 2

indexOf() will let you find position of a given entry, add(index, object) will let you insert at an index.

public static void main(String[] args) {
    List<String> names = new ArrayList<String>();

    names.add("Mary");
    names.add("John");
    names.add("Mahendra");
    names.add("Sara");
    names.add("Jose");
    names.add("Judy");

    names.add(names.indexOf("Mahendra"), "Harry");

    for (String name : names) {
        System.out.println(name);
    }
}
Share:
13,151
RazaHuss
Author by

RazaHuss

Computer Science Major. Freshman. Just getting into learning programming.

Updated on June 13, 2022

Comments

  • RazaHuss
    RazaHuss almost 2 years

    So here is my program:

    Create an ArrayList that will only contain strings Add the following to the list in order

    • Mary
    • John
    • Mahendra
    • Sara
    • Jose
    • Judy

    Print the list using the enhanced for loop Insert Harry in front of Mahendra and after John Then Remove position 4 from the list

    Here's what I've written:

    import java.util.ArrayList;
    import java.util.Scanner;
    
    public class Name {
        public static void main(String[] args) {
            ArrayList<String> names = new ArrayList<String>();
            Scanner input = new Scanner(System.in);
            names.add(input.nextLine());
            names.add(input.nextLine());
            names.add(input.nextLine());
            names.add(input.nextLine());
            names.add(input.nextLine());
            names.add(input.nextLine());
            names.add(input.nextLine());
    
            for (String n : names) {
            System.out.println(n);
            }
        }
    }
    

    I guess I'm having problems with adding and removing. I believe everything else should be fine though.

  • Yogendra Singh
    Yogendra Singh over 11 years
    @user1793131: Please don't forget to accept the answer.