简体   繁体   中英

Array list duplication in java

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM