|
||
|
||||
|
A lot of people ask me how to use an ArrayList and also ask what is the advantage of an ArrayList over a standard Array.
If the data has a known number of elements or small fixed size upper bound, arrays are often the best choice. However, many data storage problems are not that simple. The main advantage to an ArrayList is that it automatically expands as data is added. A disadvantage is that an ArrayList cannot work with primitive types. Here is a quick example to show you how to add, print, and remove data from an ArrayList: Java Code
// Import ArrayList
import java.util.ArrayList;
public class ArrayListExample {
/**
* JavaProgrammingForums.com
*/
public static void main(String[] args) {
// Construct a new empty ArrayList for type String
ArrayList<String> al = new ArrayList<String>();
// Fill ArrayList (index, String)
al.add(0, "Java");
al.add(1, "Programming");
al.add(2, "Forums");
al.add(3, ".com");
// Convert ArrayList to Object array
Object[] elements = al.toArray();
// Print Object content
for (int a = 0; a < elements.length; a++) {
System.out.println(elements[a]);
}
// Remove item from ArrayList
al.remove(3);
// Clear entire ArrayList
al.clear();
}
}
__________________
Don't forget to add code tags around your code: ![]() Forum Tip: Add to peoples reputation ( ) by clicking the button on their useful posts.
|
|
||||
|
You forgot to add that ArrayLists cannot work with primitive types.
|
| The Following User Says Thank You to Fendaril For This Useful Post: | ||
JavaPF (17-05-2009) | ||
![]() |
| Tags |
| arraylist |
| Thread Tools | |
| Display Modes | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| convert arraylist to a hash map | nadman123 | Collections and Generics | 1 | 29-07-2009 09:24 AM |
| creating objects from file input and storing in arraylist | LabX | File I/O & Other I/O Streams | 4 | 14-05-2009 08:52 AM |
| java.util.UnknownFormatConversionException error | rosh72851 | Exceptions | 4 | 29-04-2009 03:53 PM |
| How to Sort an Array using the java.util.Arrays class | JavaPF | Java Code Snippets and Tutorials | 0 | 01-12-2008 02:02 PM |
| java.util.UnknownFormatConversionException error | rosh72851 | Exceptions | 2 | 08-10-2008 04:01 PM |