-
容器: 可变长的,任意数据类型的数据的集合
-
数组:
-
定长的
-
数据类型相同
-
有序,有索引,根据索引查询效率高
-
手写简单容器:
-
自定义容器类 : 只存储字符串,实现随着内容的增删长度可变
*/
public class App01 {
public static void main(String[] args) {
MyContainer my=new MyContainer();//存储数据 my.add("惊奇队长"); my.add("美国队长"); System.out.println(my.get(0));; System.out.println(my.get(1));; System.out.println(my.getSize()); //删除元素 根据索引删除 my.remove(0); System.out.println(my.get(0));; System.out.println(my.getSize());
}
}
//自定义容器类
class MyContainer{
private String[] arr=null;
//容器中数据的个数
private int size;
public MyContainer() {
arr=new String[0];
}
/*
* 修改功能
*/
/*
* 根据索引删除数据
*/
public void remove(int index) {
if(index<0 || index>=size){
throw new ArrayIndexOutOfBoundsException("索引越界啦!!!");
}
//存储原数组
String[] temp=arr;
arr=new String[size-1];
//拷贝
for(int i=0;i<size;i++){
if(i>=index){
if(i==index){
continue;
}else{
arr[i-1]=temp[i];
}
}else{
arr[i]=temp[i];
}
}
size--;
}
/*
* 根据索引进行获取
*/
public String get(int index) {
if(index<0 || index>=size){
throw new ArrayIndexOutOfBoundsException("索引越界啦!!!");
}
return arr[index];
}
/*
* 添加方法
* 每次添加一个数据,数组进行扩容
*/
public void add(String ele) {
//存储原数组中的数据
String[] temp=arr;
arr=new String[size+1];
//数组拷贝
for(int i=0;i<size;i++){
arr[i]=temp[i];
}
arr[size]=ele;
size++;
}
//外部获取容器中数据的长度
public int getSize() {
return size;
}
}
- 集合 Collection
- 成员方法:
- 容器可以存储任意类型的数据
- 泛型中的数据类型只能为引用类型,基本数据类型会发生非自动装箱
- 遍历:
-
1.曾强for
-
2.迭代器
*/
public class CollectionDemo02 {
public static void main(String[] args) {
Collection col=new ArrayList();
Collection col2=new ArrayList();
//boolean add(E e)
col.add(“哈哈”);
col.add(123);
col.add(“hehe”);
col.add(“hengheng”);
col2.addAll(col);
System.out.println(col);
System.out.println(col2);
//void clear() 移除此 collection 中的所有元素(可选操作)。
//col2.clear();
System.out.println(col2);
//boolean contains(Object o)如果此 collection 包含指定的元素,则返回 true。
System.out.println(col.contains(“哈哈”));
//equals
System.out.println(col.equals(col2)); //比较内容,有重写
//boolean isEmpty() 如果此 collection 不包含元素,则返回 true。
System.out.println(col2.isEmpty());
//boolean remove(Object o)
System.out.println(col.remove("哈哈"));
System.out.println(col);
//removeAll(Collection)
System.out.println(col2.removeAll(col));
System.out.println(col2);
//int size() 返回此 collection 中的元素数。
System.out.println(col.size());
//Object[] toArray() 返回包含此 collection 中所有元素的数组。
col.toArray();
Object[] a=col.toArray();
System.out.println(Arrays.toString(a));
//增强for
for(Object o : col){
System.out.println(o);
}
//迭代器
//1.获取操作这个容器的迭代器对象
Iterator it=col.iterator();
//2.判断下一个是否有数据
if(it.hasNext()){
//3.获取写一个数据
System.out.println(it.next());
}
//增强程序的稳定性和可读性
//泛型 :定义规范容器中所有元素的数据类型,强制规范,如果不符合报错
Collection<String> col3=new ArrayList();
col3.add("呵呵");
// col3.add(15);
}
}