生活随笔
收集整理的這篇文章主要介紹了
自定义ArrayList
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
ArrayList是通過數組實現的。
實現ArrayList類中的以下功能:
size():列表的大小isEmpty():判斷列表是否為空clear():清空整個列表get(int index):獲取下標為index的值set(int index,Object value):修改下標為index的值add(Object value):向列表中(也就是在列表的最后)添加數據remove(int index):刪除下標為index的值實現ArrayList的迭代器(Iterator),實現hasnext()、next()、remove()方法。注意:這里并沒有實現remove()方法必須在next()方法之后調用的邏輯
package com.test.test;import java.util.Iterator;
import java.util.NoSuchElementException;
public class Test2 {
public static void main(String[] args) {MyArrayList<String> mList =
new MyArrayList<String>();mList.add(
"我");mList.add(
"是");mList.add(
"大");mList.add(
"小");mList.add(
"牛");mList.add(
"奶");
mList.
set(
0,
"你");
for (
int i =
0; i < mList.size(); i++) {String
value = (java.lang.String) mList.
get(i);System.
out.println(
value);}
}}
class MyArrayList<String> implements Iterable<String> {
private int theSize;
private Object[] theItems;
private static final
int DEFAULT_LENGTH =
10;
public void clear() {theSize =
0;ensureCapacity(DEFAULT_LENGTH);}
public int size() {
return theSize;}
public boolean
isEmpty() {
return size() ==
0;}
public Object
get(
int index) {
if (index <
0 || index >= size()) {
throw new ArrayIndexOutOfBoundsException();}
return theItems[index];}
public Object
set(
int index,Object
value){
if(index<
0||index>=size()){
throw new ArrayIndexOutOfBoundsException();}Object oldItem = theItems[index];theItems[index] =
value;
return oldItem;}
public boolean
add(Object
value){add(size(),
value);
return true;}
public void add(
int index,Object
value) {ensureCapacity(index);
for(
int i=index;i<size();i++){theItems[i+
1] = theItems[i];}theItems[index] =
value;theSize++;}
public Object
remove(
int index) {Object removeItem = theItems[index];
for(
int i=index;i<size()-
1;i++){theItems[i] = theItems[i+
1];}theSize--;
return removeItem;}
public void ensureCapacity(
int newCapacity) {
if (newCapacity < theSize) {
return;}
else {Object[] old = theItems;theItems =
new Object[newCapacity+
1];
for (
int i =
0; i < size(); i++) {theItems[i] = old[i];}}}@Override
public Iterator<String>
iterator() {
return new ArrayListIterator();}
private class ArrayListIterator implements Iterator<String>{
private int current =
0;@Override
public boolean
hasNext() {
return current<size();}@Override
public String
next() {
if(!hasNext()){
throw new NoSuchElementException();}
return (String) theItems[current++];}@Override
public void remove() {MyArrayList.
this.remove(--current);}}}
打印結果:
總結
以上是生活随笔為你收集整理的自定义ArrayList的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。