📄 arraylistexample.java
字号:
import java.util.ArrayList;public class ArrayListExample { public void doExample() { ArrayList myList = new ArrayList(5); // set initial array capacity to 5 // load the list with integers 0-4 wrapped in Integer for ( int i=0; i<5; i++) { myList.add( new Integer(i) ); } System.out.println( "List contains " + myList.size() + " elements" ); // locate a specific object in the list Integer int2 = new Integer(2); System.out.println( "List contains Integer(2): " + myList.contains(int2) ); System.out.println( "Integer(2) is at index " + myList.indexOf(int2) ); // replace an object and then locate it by index myList.set(2, new Integer(99)); System.out.println( "Get element at index 2: " + myList.get(2) ); // add 5 more elements - capacity will grow automatically for ( int i=5; i<10; i++) { // add by specifying the index myList.add( i, new Integer(i) ); } // add 5 more elements, but increase the capacity first myList.ensureCapacity(15); for ( int i=10; i<15; i++) { myList.add( new Integer(i) ); } // take the last 5 elements back out and reduce the capacity myList.subList(10,15).clear(); myList.trimToSize(); // create another list and copy it into the original one ArrayList otherList = new ArrayList(); otherList.add( new String("otherList 1") ); otherList.add( new String("otherList 2") ); myList.add(7,otherList); // display the list elements System.out.println(myList); } public static void main( String args[] ) { new ArrayListExample().doExample(); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -