Home > database >  Array list duplication in java
Array list duplication in java

Time:12-19

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);
  }
}

CodePudding user response:

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.
  }
}

CodePudding user response:

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);
  •  Tags:  
  • java
  • Related