So here is my program:
Create an ArrayList that will only contain strings Add the following to the list in order
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.
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);
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With