Home > Java > javaTutorial > The specific implementation of dynamic arrays in java

The specific implementation of dynamic arrays in java

王林
Release: 2019-11-30 16:10:02
forward
2483 people have browsed it

The specific implementation of dynamic arrays in java

Statement:

data is the array name.

size is the next position of the last element in the array.

Reasons for implementing dynamic arrays:

Because arrays in Java are static, you need to specify the size of the array when you create a new array. If the elements that need to be stored are For unknown numbers, if the space is set too large, it will cause waste. If the space is set too small, all data will not be stored. We can use the resize() method we wrote to achieve automatic expansion and no longer worry about the array capacity.

When automatic expansion or automatic shrinkage is required, it is usually when the array is full or there is too much free space in the array, which mostly occurs during add and delete operations.

When size == data.length, it means the array is full, call the resize(int newCapacity) method, and pass in 2*data as the parameter. length means that the length of the newly created array is twice the length of the original array.

Related video tutorial recommendations: java course

Whensize == data.length /4 and data.length/2! = 0, call the resize method to reduce the size.

The parameter defaults to 1.5*capacity in the automatic expansion method of ArrayList.

In the implementation of the resize() method, a new array named newData is created to receive the elements in the original array. Use a for loop to transfer elements in the array.

add method implementation

//向指定位置添加元素e
	public void add(int index,E e){
		if(index<0||index>size){
			throw new IllegalArgumentException("AddLast failed.Require index error");

		}
		if(size == data.length){
			resize(2*data.length);
		}
		
		for (int i = size-1; i >= index; i--) {
			data[i+1] = data[i];
		}
		data[index] = e;
		size++;
	}
Copy after login

remove method implementation

//删除元素,并返回被删除的元素
	public E remove(int index){
		if(index<0 || index >=size){
			throw new IllegalArgumentException("Remove failed. Index is illegal");
		}
		E ret = data[index];
		for (int i = index+1; i < size; i++) {
			data[i-1] = data[i];
		}
		size--;
		data[size] = null;//loitering objects  != memory leak
		
		if(size == data.length /4 && data.length/2 != 0){
			resize(data.length/2);
		}
		return ret;
	}
Copy after login

resize method implementation

private void resize(int newCapacity){
		E[] newData = (E[])new Object[newCapacity];
		for (int i = 0; i < size; i++) {
			newData[i] = data[i];
		}
		data = newData;
	}
Copy after login

Array class

package array;
public class Array {
	private E[] data;
	private int size;
	@SuppressWarnings("unchecked")
	public Array(int capacity){
		data = (E[]) new Object[capacity];
		size = 0;
	}
	public Array(){
		this(10);
	}
	public int getSize(){
		return size;
	}
	public int getCapacity(){
		return data.length;
	}
	public boolean isEmpty(){
		return size == 0;
	}
	//向第一个位置添加一个元素
	public void addFirst(E e){
		add(0,e);
	}
	//向最后一个位置添加一个元素
	public void addLast(E e){
		add(size,e);
	}
	//向指定位置添加元素e
	public void add(int index,E e){
		if(index<0||index>size){
			throw new IllegalArgumentException("AddLast failed.Require index error");
		}
		if(size == data.length){
			resize(2*data.length);
		}
		for (int i = size-1; i >= index; i--) {
			data[i+1] = data[i];
		}
		data[index] = e;
		size++;
	}
	//获取index位置的元素e
	public E get(int index){
		if(index<0 || index >=size){
			throw new IllegalArgumentException("Get failed. Index is illegal");
		}
		return data[index];
	}
	//修改index索引位置的元素e
	public void set(int index, E e){
		if(index<0 || index >=size){
			throw new IllegalArgumentException("Get failed. Index is illegal");
		}
		data[index] = e;
	}
	//判断元素是否存在于数组中
	public boolean contains(E e){
		for (int i = 0; i < size; i++) {
			if(data[i].equals(e)){
				return true;
			}
		}
		return false;
	}
	//找到元素并返回索引
	public int find(E e){
		for (int i = 0; i < size; i++) {
			if(data[i].equals(e)){
				return i;
			}
		}
		return -1;
	}
	//删除元素,并返回被删除的元素
	public E remove(int index){
		if(index<0 || index >=size){
			throw new IllegalArgumentException("Remove failed. Index is illegal");
		}
		E ret = data[index];
		for (int i = index+1; i < size; i++) {
			data[i-1] = data[i];
		}
		size--;
		data[size] = null;//loitering objects  != memory leak
		
		if(size == data.length /4 && data.length/2 != 0){
			resize(data.length/2);
		}
		return ret;
	}
	public E removeFirst(){
		return remove(0);
	}
	public E removeLast(){
		return remove(size-1);
	}
	//从数组中删除元素e
	public void removeElement(E e){
		int index = find(e);
		if(index != -1){
			remove(index); 
		}
	}
	@Override
	public String toString(){
		StringBuilder res = new StringBuilder();
		res.append(String.format("Array:size = %d ,capacity = %d\n",size,data.length));
		res.append('[');
		for (int i = 0; i < size; i++) {
			res.append(data[i]);
			if(i != size-1){
				res.append(",");
			}
		}
		res.append(']');
		return res.toString();
	}
	private void resize(int newCapacity){
		E[] newData = (E[])new Object[newCapacity];
		for (int i = 0; i < size; i++) {
			newData[i] = data[i];
		}
		data = newData;
	}
}
Copy after login

Main test:

package array;

public class Main {
	public static void main(String[] args){
		Array<Integer> arr = new Array<>();
		for (int i = 0; i < 10; i++) {
			arr.addLast(i);
		}
		System.out.println(arr);
		arr.add(1, 100);
		System.out.println(arr);
		arr.addFirst(-1);
		System.out.println(arr);
		arr.set(0, 1);
		System.out.println(arr);
	}
}
Copy after login

For more related articles and tutorials, please visit:Introduction to java development

The above is the detailed content of The specific implementation of dynamic arrays in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template