List介面的特有方法(帶索引的方法)
阿新 • • 發佈:2018-11-08
A:List介面的特有方法(帶索引的方法)
a:增加元素方法
add(Object e):向集合末尾處,新增指定的元素
add(int index, Object e) 向集合指定索引處,新增指定的元素,原有元素依次後移
/* * add(int index, E) * 將元素插入到列表的指定索引上 * 帶有索引的操作,防止越界問題 * java.lang.IndexOutOfBoundsException * ArrayIndexOutOfBoundsException * StringIndexOutOfBoundsException */ public static void function(){ List<String> list = new ArrayList<String>(); list.add("abc1"); list.add("abc2"); list.add("abc3"); list.add("abc4"); System.out.println(list); list.add(1, "itcast"); System.out.println(list); }
b:刪除元素刪除
remove(Object e):將指定元素物件,從集合中刪除,返回值為被刪除的元素
remove(int index):將指定索引處的元素,從集合中刪除,返回值為被刪除的元素
/* * E remove(int index) * 移除指定索引上的元素 * 返回被刪除之前的元素 */ public static void function_1(){ List<Double> list = new ArrayList<Double>(); list.add(1.1); list.add(1.2); list.add(1.3); list.add(1.4); Double d = list.remove(0); System.out.println(d); System.out.println(list); } c:替換元素方法 set(int index, Object e):將指定索引處的元素,替換成指定的元素,返回值為替換前的元素 /* * E set(int index, E) * 修改指定索引上的元素 * 返回被修改之前的元素 */ public static void function_2(){ List<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(3); list.add(4); Integer i = list.set(0, 5); System.out.println(i); System.out.println(list); }
d:查詢元素方法
get(int index):獲取指定索引處的元素,並返回該元素