package array
import scala.reflect.ClassTag
/**
* Copyright (c) 2019 qingzhi.wu ALL Rights Reserved
*
* Project: arithmetic
* Package: array
* Version: 1.0
* Created by HeartisTiger on 2019/9/15 13:40
*/
class MyArray[E:ClassTag] {
private var data= new Array[E](10)
private var size:Int = _
/**
* 辅助构造器
* @param capacity 构建数组的容量
*/
def this(capacity:Int){
this()
if(capacity <= 0){
throw new IllegalArgumentException("容量不能小于等于0,必须是大于0的")
}
this.data = new Array[E](capacity)
this.size = 0
}
def getSize():Int ={
return size
}
def getCapacity():Int ={
return data.length
}
/**
* 在index这个位置插入一个新元素e
* @param index
* @param e
*/
def add(index:Int,e:E)={
if(index < 0 || index > size)
throw new IllegalArgumentException("添加错误,应该index小于等于当前data中的元素个数")
if(size == data.length){
resize(getCapacity()*2)
}
for(i <- index to size-1 reverse){
data(i+1) = data(i)
}
data(index) = e
size += 1
}
private def resize(newCapacity:Int)={
val newData = new Array[E](newCapacity)
for(i <- 0 until size){
newData(i) = data(i)
}
data = newData
}
/**
* 尾部添加一个元素
* @param e 为泛型指定的一个元素
*/
def addLast(e:E)={
add(size,e)
}
def addFirst(e:E)={
add(0,e)
}
def show()={
printf(" Size=%d,Capacity=%d,data[%s] \n",getSize(),getCapacity(),data.slice(0,size).mkString(","))
}
def get(index:Int):E ={
if(index >= size || index < 0)
throw new ArrayIndexOutOfBoundsException("index 必须大于我们的容量,和必须大于等于0")
return data(index)
}
def set(index:Int,e:E): Unit ={
if(index >= size || index < 0)
throw new ArrayIndexOutOfBoundsException("index 必须大于我们的容量,和必须大于等于0")
data(index) = e
}
def contains(e:E): Boolean ={
for (i <- 0 until size){
if(data(i).equals(e)){
return true
}
}
return false
}
def find(e:E):Int ={
for (i <- 0 until size){
if(data(i).equals(e)){
return i
}
}
return -1
}
def remove(index:Int):E={
val e = get(index)
for(i <- index until size-1){
data(i) = data(i+1)
}
size -= 1
if(size == data.length /2){
resize(data.length /2)
}
return e
}
def removeFirst(): Unit ={
return remove(0)
}
def removeLast(): Unit ={
return remove(size-1)
}
def removeElement(e:E): Unit ={
val i = find(e)
remove(i)
}
}
测试
package array
/**
* Copyright (c) 2019 qingzhi.wu ALL Rights Reserved
*
* Project: arithmetic
* Package: array
* Version: 1.0
* Created by HeartisTiger on 2019/9/15 13:54
*/
object Main {
def main(args: Array[String]): Unit = {
val array = new MyArray[Int]
for(i <- 1 to 20){
array.addLast(i)
}
for (i <- 1 to 11){
array.removeLast()
}
array.addLast(11)
array.show()
}
}