java-数组容器-插入练习:
package com.etc.liebiao;
public class Student1 {
private String id;
public String name;
public Student1(){}
public Student1(String id,String name){
this.id = id;
this.name = name;
}
@Override
public String toString() {
return String.format("(%S,%S)",name,id);
}
public String getId(){
return id;
}
public void setId(String id){
this.id = id;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
}
package com.etc.liebiao;
/**
* Container 容器 : 数组就是一个容器
* 数组容器的缺点 : 1. 容量固定无法扩展。既不能太大也不能太小,很难确定;
* 2.插入和删除困难,插入对象代价很多,需要挪动现有对象。
*/
public class RongQi {
public static void main(String[] args) {
Student1[] s = new Student1[4];
s [0] = new Student1("2020001", "sf");
s [1] = new Student1("2020002", "xz");
s [2] = new Student1("2020003", "xw");
s [3] = null;
for (int i = 0; i < s.length; i++) {
System.out.println(s[i]);
}
// 数组插入需要挨个调换位置:比较麻烦
s[3] = s[2];
s[2] = s[1];
s[1] = new Student1("2020004","xl");
for (int i = 0; i < s.length; i++) {
System.out.println(s[i]);
}
System.out.println("exit");
}
}
本文通过一个简单的 Java 示例展示了数组作为容器的使用,强调了其容量固定和插入操作不便的缺点。代码创建了一个 Student1 类,并在 RongQi 类中初始化了一个 Student1 对象数组,演示了插入新对象时需要挪动已有元素的过程,揭示了数组容器在动态调整大小和插入操作上的局限性。
1万+

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



