码迷,mamicode.com
首页 > 其他好文 > 详细

线性表

时间:2017-06-20 19:39:15      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:sina   index   new   for   package   length   nts   city   clear   

这个比较重要希望看完能理解

代码如下:

十个方法:
package Day07;

import java.util.Arrays;

public class MyArrayList {
public static final int DEFAULT_CAPACITY = 1;
private int size = 0;
private Object[] elements;
/**
*
*/
public MyArrayList() {
this.size = 0;
this.elements = new Object[DEFAULT_CAPACITY];
}
public int getSize() {
return size;
}
public Object[] getElements() {
return elements;
} public void add(Object o) {
if (size >= elements.length) {
Object[] temp = new Object[elements.length * 2];
for (int i = 0; i < elements.length; i++) {
temp[i] = elements[i];
}
elements = temp;
}
elements[size++] = o;
}

public void add(int index, Object o) {
if (size >= elements.length) {
Object[] temp = new Object[elements.length * 2];
for (int i = 0; i < elements.length; i++) {
temp[i] = elements[i];
}
elements = temp;
}
elements[index] = o;
size++;
}

public void clear() {
for (int i = 0; i < size; i++) {
elements[i] = null;
}
}

public boolean contains(Object o) {
boolean isInArray = false;
for (int i = 0; i < size; i++) {
if (elements[i].equals(o)) {
isInArray = true;
break;
}
}
return isInArray;
}

public Object get(int index) {
return elements[index];
}

public int indexOf(Object o) {
int index = -1;
for (int i = 0; i < size; i++) {
if (elements[i].equals(o)) {
index = i;
break;
}
}
return index;
}

public boolean isEmpty() {
return this.size == 0;
}

public void set(int index, Object o) {
if (index >= 0 && index < size) {
elements[index] = o;
} else {
System.out.println("index out of bound.");
}
}

public int size() {
return this.size;
}

public static void main(String[] args) {
MyArrayList arr1 = new MyArrayList();
arr1.add("abc");
arr1.add("123");
System.out.println(Arrays.toString(arr1.getElements()));
System.out.println(arr1.contains("123"));
System.out.println(arr1.contains("1"));
}
}

线性表

标签:sina   index   new   for   package   length   nts   city   clear   

原文地址:http://www.cnblogs.com/F001li/p/7055909.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!