Dave's Brain

Browse - Programming Tips - How can I prepend (add at the start) an element to a ArrayList ?

Date: 2012may3
Language: Java

Q.  How can I prepend (add at the start) an element to a ArrayList ?

A.  Use add() with 0 as the first parameter (the position).

void prepend(ArrayList<String> list, final String first) { list.add(0, first); } // Example use: ArrayList<String> a = new ArrayList<String>(); a.add("one"); a.add("two"); a.add("three"); prepend(a, "Top"); for (int i = 0; i < a.size(); i++) { System.out.println(i + "=" + a.get(i)); }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.