首页 > 其他 > 详细

线性表

时间:2017-06-20 19:34:51      阅读:313      评论:0      收藏:0      [点我收藏+]

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

代码如下:

十个方法:
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"));
}
}

线性表

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!