java中对数组元素进行增减,不可再原数组上操作,开辟一个新数组通过一一赋值接受增减后的原数组,最后再用arr=newarr;二者指向堆空间的同一内容。
堆空间用于存储new出来的对象或数组。在堆中产生了一个数组或者对象后,还可以在栈中定义一个特殊的变量,这个变量对应数组或者对象在堆内存中的首地址,通过该地址值指向堆空间。
这就是 Java 中的指针
public class Main {
public static void main(String[] args) {
// write your code here
Array<Integer> arr=new Array<>();
for (int i=0;i<10;i++){
arr.addLast(i);
}
System.out.println(arr);
arr.add(10,100);
System.out.println(arr);
arr.add(2,300);
System.out.println(arr);
}
}
/**
* @author admin
* @version 1.0.0
* @ClassName Array.java
* @Description TODO
* @createTime 2021年08月21日 08:11:00
*/
public class Array<E> {
//private私有,封装性好,避免用户直接修改。
private E[] data;
private int size;
//构造器,用传入的容量capacity构造Array。
public Array(int capacity){
data= (E[])new Object[capacity];//只能这样构建
size=0;
}
//无参数构造器,默认容量capacity=10.
public Array(){
this(10);
}
//获取数组中元素个数
public int getSize(){
return size;
}
//获取数组容量
public int getCapacity(){
return data.length;
}
//数组是否为空。
public boolean isEmpty(){
return size==0;
}
//向所有元素后添加一个新元素
public void addLast(E element){
if (size==data.length)
throw new IllegalArgumentException("添加失败,数组满了");
data[size]=element;
size++;
//即可以调用下面的方法,add(size,e);
}
//在index位置插入一个新元素e
public void add(int index,E e){
if (index<0||index>size){
throw new IllegalArgumentException("添加失败,index必须在0到size之间");
}
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++;
}
public void resize(int newcapacity){
E[] newdata=(E[])new Object[newcapacity];
for (int i = 0; i < size; i++) {
newdata[i]=data[i];
}
data=newdata;
}
//获取index索引位置处的元素。
public E get(int index){
if (index<0||index>=size)
throw new IllegalArgumentException("超了");
return data[index];
}
//修改指定位置的元素。
public void set(int index,E e){
if (index<0||index>=size)
throw new IllegalArgumentException("超了");
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("超了");
E t=data[index];
for (int i=index+1;i<size;i++){
data[i-1]=data[i];
}
size--;
return t;
}
@Override//重写toString方法。
public String toString(){
StringBuffer res=new StringBuffer();
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();
}
}
本文详细介绍了如何在Java中对数组元素进行增删操作,强调了不能直接在原数组上修改并需创建新数组。通过示例代码展示了Array类的实现,包括添加元素、扩容、修改元素等方法。同时,解释了Java中的堆空间概念,以及如何通过栈中的引用指向堆中的数组对象。
111

被折叠的 条评论
为什么被折叠?



