写一个MyArrayList类,重写List中的方法
发布网友
发布时间:2024-01-02 14:56
我来回答
共1个回答
热心网友
时间:2024-06-13 05:03
import java.util.Arrays;
public class ListOfMy{
private Object[] obj;
private int num=0;
public ListOfMy(){
obj=new Object[0];
}
public int size(){
return num;
}
public boolean isEmpty() {
if(obj==null || obj.length<1){
return true;
}
return false;
}
public boolean contains(Object element) {
for(int i=0; i<obj.length; i++){
if(obj[i].equals(element)){
return true;
}
}
return false;
}
public boolean add(Object element) {
if(element!=null){
num++;
obj=Arrays.copyOf(obj, num);
obj[num-1]=element;
return true;
}
return false;
}
public boolean remove(Object element){
boolean f=false;
for(int i=0,j=0; i<obj.length; i++){
if(!obj[i].equals(element)){
obj[j++]=obj[i];
f=true;
}
}
if(f){
obj=Arrays.copyOf(obj, --num);
}
return f;
}
public void clear() {
obj=new Object[0];
num=0;
}
public Object get(int index)throws Exception{
if(index<0 || index>num){
throw new Exception("index无效");
}
return obj[index];
}
public int set(int index, Object element)throws Exception{
if(index<0 || index>num){
throw new Exception("index无效");
}
obj[index]=element;
return index;
}
public void insert(int index, Object element)throws Exception{
if(index<0 || index>num){
throw new Exception("index无效");
}
num++;
obj=Arrays.copyOf(obj, num);
for(int i=0; i<index; i++){
obj[i]=obj[i];
}
for(int i=num-1; i>index; i--){
obj[i]=obj[i-1];
}
obj[index]=element;
}
public Object remove(int index)throws Exception{
if(index<0 || index>num){
throw new Exception("index无效");
}
Object ob=null;
for(int i=0, j=0;i<num;i++){
if(i!=index){
obj[j]=obj[i];
j++;
}else{
ob=obj[i];
}
}
if(null!=ob){
obj=Arrays.copyOf(obj, --num);
}
return ob;
}
public int indexOf(Object element) {
for(int i=0; i<obj.length; i++){
if(obj[i].equals(element)){
return i;
}
}
return -1;
}
public String toString(){
StringBuilder sb=new StringBuilder("[");
for(int i=0; i<num; i++){
if(i>0)sb.append(",");
sb.append(obj[i]);
}
sb.append("]");
return sb.toString();
}
}
基本的,请参数,有不对的地方,请自己调试、修改