1

I have an array list of String element I want to duplicate last element of that list and that duplicate element set in the 0th position of same list. how to duplicate array list.

below is my input list:

List ["Apple","Tomato","Patato","Brinjal","Cabbage"]

I want below type of list as output:

List ["Cabbage","Apple","Tomato","Patato","Brinjal","Cabbage"]
public class Main {
  public static void main(String[] args) {
    ArrayList<String> cars = new ArrayList<String>();
    cars.add("Apple");
    cars.add("Tomato");
    cars.add("Patato");
    cars.add("Cabbage");
    System.out.println(cars);
  }
}
6
  • 1
    Try cars.add(0, cars.get(cars.size() - 1)) Commented Dec 18, 2022 at 6:46
  • 1
    Question, why are you adding foods to a list called cars? Just curious. Commented Dec 18, 2022 at 6:47
  • Really oddly named cars? Commented Dec 18, 2022 at 6:49
  • Did you search? Did you look through the docs? Did you try something? Commented Dec 18, 2022 at 7:14
  • Note: Doing something like cars.add(0, cars.get(cars.size() - 1)) will work, but that makes the first and last element the same instance; this may be okay for an immutable object like instances of String, but for mutable objects this could lead to unintended side effects. Commented Dec 18, 2022 at 7:19

2 Answers 2

3

You can do something like this:

import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList<String> cars = new ArrayList<String>();
    cars.add("Apple");
    cars.add("Tomato");
    cars.add("Patato");
    cars.add("Cabbage");

    // Geting the last element of the list
    String lastElement = cars.get(cars.size() - 1);

    // Adding the last element to the starting of the list
    cars.add(0, lastElement);

    System.out.println(cars);  // This should out put your expected result.
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Since you specify needing a copy of the list, you might add the last element to an empty ArrayList<String> then use addAll to add the original list elements.

ArrayList<String> copiedArraylist = new ArrayList<String>();
copiedArraylist.add(cars.get(cars.size()-1);
copiedArraylist.addAll(1, cars);

Comments