Skip to content

Instantly share code, notes, and snippets.

@mizushou
Created October 7, 2017 23:55
Show Gist options
  • Save mizushou/940e1efdb5c526609f7229b76f955932 to your computer and use it in GitHub Desktop.
Save mizushou/940e1efdb5c526609f7229b76f955932 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
class ArrayListDemo1 {
public static void main(String[] args) {
//1. addしてみる
ArrayList<Integer> array = new ArrayList<>();
System.out.println("===========");
System.out.println("Before add");
System.out.println("===========");
System.out.println("array size : " + array.size());
array.add(10);
array.add(20);
array.add(30);
array.add(40);
array.add(50);
array.add(60);
System.out.println("===========");
System.out.println("After add");
System.out.println("===========");
System.out.println("array size : " + array.size());
System.out.print("array elements :");
showElements(array);
System.out.println("");
//2. index指定でaddしてみる
System.out.println("===========");
System.out.println("After add(i,e)");
System.out.println("===========");
array.add(0,1);
System.out.println("array size : " + array.size());
System.out.print("array elements :");
showElements(array);
System.out.println("");
//3. setで置換してみる
System.out.println("===========");
System.out.println("After set()");
System.out.println("===========");
array.set(6,6);
System.out.println("array size : " + array.size());
System.out.print("array elements :");
showElements(array);
System.out.println("");
}
static void showElements(ArrayList a) {
System.out.print("[ ");
for(int i = 0; i < a.size(); i++) {
System.out.print(a.get(i) + " ");
}
System.out.print("]");
}
}
@mizushou
Copy link
Author

mizushou commented Oct 8, 2017

  • ArrayListで要素の追加、置換
  • キャパシティを指定してArrayListを用意しても、要素が入っていなければindex指定のaddはエラーになる。indexは要素の位置。つまり、sizeが0の状態ではindex指定のaddは使えない。
    static ArrayList<Integer> S = new ArrayList<Integer>(10); S.add(index,element);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment