ArrayList集合类和对象数组案例区别讲解

目录

对象数组案例讲解

 集合

ArrayList类的构造方法和成员方法

对象数组案例讲解

  • 创建一个学生数组,存储三个学生对象并遍历
package com.demo01;
/**
 * 
 * @author 无限嚣张菜菜
 * 分析:
 * 	A:定义学生类
 * 	B:创建学生数组
 * 	C:创建学生对象
 * 	D:把学生对象作为元素赋值给学生数组
 * 	E:遍历学生数组
 *
 */

public class StudentDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// 创建数组对象,创建的是一个类对象
		student[] students = new student[3];
		
		// 创建学生对象,初始值
		student s1 = new student("张三",26);
		student s2 = new student("李四",28);
		student s3 = new student("王五",30);
		
		//把学生对象作为元素赋值为学生数组
		students[0] = s1;
		students[1] = s2;
		students[2] = s3;
		
		//遍历学生数组,students 是一个数组对象
		for(int i=0;i<3;i++) {
			student s = students[i];
			System.out.println(s.getName()+"---------"+s.getAge());
		}

	}

}

 集合

为什么出现集合类?

我们学习的是面向对象语言,而面向对象语言对事物的描述是通过对象体现的,为了方便对多个对象进行操作,我们就必须把这多个对象进行存储。而要想存储多个对象,就不能是一个基本的变量,而应该是一个容器类型的变量,在我们目前所学过的知识里面,有哪些是容器类型的呢?数组和StringBuilder。但是呢? StringBuilder的结果是一个字符串,不一定满足我们的要求,所以我们只能选择数组,这就是对象数组。而对象数组又不能适应变化的需求,因为数组的长度是固定的,这个时候,为了适应变化的需求,Java就提供了集合类供我们使用。由此可见集合的长度是可变的。

ArrayList类的构造方法和成员方法

  • 构造方法

        –ArrayList()

  • 成员方法

        –添加元素 

        –获取元素

        –集合长度

        –删除元素

        –修改元素

package com.demo01;

import java.util.ArrayList;

/*
 * 获取元素
 * 		public E get(int index):返回指定索引处的元素
 * 集合长度
 * 		public int size():返回集合中元素的个数
 * 删除元素
 * 		public boolean remove(Object o):删除指定元素,返回删除是否成功
 * 		public E remove(int index):删除指定索引处的元素,返回被删除的元素
 * 修改元素
 * 		public E set(int index,E element):修改指定索引处的元素,返回被修改的元素
 */
public class ArrayListDemo2 {
	public static void main(String[] args) {
		// 创建集合列表
		ArrayList<String> array = new ArrayList<String>();
		
		//增加元素
		array.add("hello");
		array.add("world");
		array.add("java");
		
		//public E get(int index):public E get(int index):返回指定索引处的元素
		System.out.println("get:"+array.get(0));
		System.out.println("get:"+array.get(1));
		System.out.println("get:"+array.get(2));
		
		//public int size():返回集合中元素的个数
		System.out.println("size:"+array.size());
		
		//public boolean remove(Object o):删除指定元素,返回删除是否成功
		System.out.println("remove:"+array.remove("world"));//true
		System.out.println(array);
		System.out.println("remove:"+array.remove("world"));//false
		
		//public E remove(int index):删除指定索引处的元素,返回被删除的元素
		System.out.println("remove:"+array.remove(1));
		System.out.println(array);
		array.add("zy");
		//public E set(int index,E element):修改指定索引处的元素,返回被修改的元素
		System.out.println("set:"+array.set(1, "android"));
		
		//输出最后结果
		System.out.println("array:"+array);
	}
}

区别:ArrayList类也可以看成一个数组对象,只不过是一个长度可变的数组对象。

猜你喜欢

转载自blog.csdn.net/zywcxz/article/details/128815401