码迷,mamicode.com
首页 > 编程语言 > 详细

数组学习1

时间:2015-02-06 14:47:24      阅读:95      评论:0      收藏:0      [点我收藏+]

标签:

package ch01;

public class MyArray {

	//需要一个真实的数组
	private long [] arr;
	
	private int elements;//数据元素的个数
	
	public MyArray(){
		arr = new long[50];
	}
	
	public MyArray(int maxsize){
		arr = new long[maxsize];
	}
	//添加数据的方法
	public void insert(long value){
		arr[elements] = value;
		elements++;
		
		
	}
	//显示的方法
	public void display(){
		System.out.print("[");
		for(int i=0;i<elements;i++){
			System.out.print(arr[i]+"  ");
		}
		System.out.print("]");
		System.out.println();
	}
	
	//查找数据的方法,查找数据根据值来查找,返回值的下标
	public int search(long value){
		int i;
		for(i=0;i<elements;i++){
			if(arr[i] == value){
				break;
			}
		}
		if(i == elements){
			return -1;
		}else{
			return i;
		}
		
		
		
	}
	
	//查找数据,根据索引返回值
	public long get(int index){
		//判断数组是不是越界
		if(index < 0 || index >= elements){
			throw new ArrayIndexOutOfBoundsException("数组越界");
		}else{
			return arr[index];
		}
		
		
		
	}
	
	//删除数据
	public void delete(int index){
		if(index >=elements || index < 0){
			throw new ArrayIndexOutOfBoundsException("数组越界");
		}else{
			for(int i=index;i<elements;i++){
				arr[index] = arr[index+1];
			}
			//数组的长度--
			elements--;
		}
		
		
		
		
	}
	
	//更新数据
	public void change(int index,int newvalue){
		
		if(index >= elements || index < 0) {
			throw new ArrayIndexOutOfBoundsException();
		} else {
			arr[index] = newvalue;
		}

		
	}
	
	
	
	
	
	
	
	
	
	
	
	
}

  

数组学习1

标签:

原文地址:http://www.cnblogs.com/aicpcode/p/4276925.html

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