JAVA basics-collection framework (1) object array creation, iterator principle, collection traversal from collection to array traversal, iterator traversal, basic function test of Collection

1. Introduction

Case 1: Requirements: 5 students, please store the information of these 5 students in an array, traverse the array, and get the information of each student.
Step 1: Create a Student class

public class Student {
    
    
	private String name;
	private int age;
	public String getName() {
    
    
		return name;
	}
	public void setName(String name) {
    
    
		this.name = name;
	}
	public int getAge() {
    
    
		return age;
	}
	public void setAge(int age) {
    
    
		this.age = age;
	}
	public Student() {
    
    
		super();
		
	}
	public Student(String name, int age) {
    
    
		super();
		this.name = name;
		this.age = age;
	}
//注意此处一定要写一个toString方法,
//否则打印出的结果会是对象数组的单个地址
	@Override
	public String toString() {
    
    
		return "Student [name=" + name + ", age=" + age + "]";
	}
}

Step 2: Main function

public class ObjectArray {
    
    
	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		//int[]arr = new int[5]; 									
//创建基本数据类型
		Student [] arr = new Student[5];						
//创建引用数据类型
		arr[0]=new Student("张三",11);							
//创建一个学生对象,存储在数组的第一个位置
		arr[1]=new Student("李四",12);						
//创建一个学生对象,存储在数组的第二个位置
		arr[2]=new Student("王二",13);							
//创建一个学生对象,存储在数组的第三个位置
		arr[3]=new Student("汾九",14);							
//创建一个学生对象,存储在数组的第四个位置
		for (int i = 0; i < arr.length; i++) {
    
    
			System.out.println(arr[i]);
		}
	}
}

The effect is as follows:
Insert picture description here

tips: What is stored in the array is not an object, but a record object address value. When we are new, we are storing in the heap in memory

Second, the collection framework

  1. The origin of the collection The
    length of the array is fixed. When the added element exceeds the length of the array, it is necessary to redefine the array. It is too troublesome. Java provides us with a collection class that can store any object. The length can be changed. Increases with the increase, decreases with the decrease of elements

  2. The difference between array and collection

  • Difference 1:
  • Arrays can store both basic data types and reference data types. Basic data types store values, and reference data types store address values.
  • The collection can only store reference data types (objects). Basic data types can also be stored in the collection, but it will be automatically boxed into an object when it is stored. For example, if a 100 is stored, it will automatically be encapsulated into new Integer(100)
  • Difference 2:
  • The length of the array is fixed and cannot grow automatically
  • The length of the collection is variable and can grow according to the increase of elements
  1. When to use arrays and collections, arrays
    are recommended if the number of elements is fixed, and collections are recommended if the number of elements is not fixed.

  2. The architecture diagram of the collection framework (this figure is very important)
    Collection frame
    Here we introduce the Collection part. That is, the main parent class of all collection methods

Third, the collection framework (the basic function test of the Collection collection

Basic function demonstration

  1. boolean add(E e) The
    add method always returns true if it is a List collection, because the List collection always returns true, because the elements in the List collection can be stored repeatedly, if it is a set collection, it returns false
Collection collection =new ArrayList();			
//父类引用指向子类对象
		boolean b1 =collection.add("abc");
		boolean b2 =collection.add(true);				
//自动装箱 new Boolean()
		boolean b3 =collection.add(100);				
		boolean b4 =collection.add(new Student("zhangsan",123)); 
		boolean b5 =collection.add("abc");				
		//当存储重复的时候ArrayList方法永远返回true,
		//但是Collection方法中List集合添加对象返回true即可													
		//但是set集合不能放置重复对象
		System.out.println(b1);
		System.out.println(b2);
		System.out.println(b3);
		System.out.println(b4);
		System.out.println(b5);
		System.out.println(collection.toString());		
		//ArrayList中没有toString方法的重写,但是父类有toString()方法

The effect is as follows:
Insert picture description here

2. boolean remove(Object o)

Delete specified element

Collection collection =new ArrayList();
		collection.add("a");
		collection.add("b");
		collection.add("c");
		collection.add("d");
		collection.remove("b");
		System.out.println(collection.toString());		//删除指定元素

The effect is as follows:
to
3. void clear()
clears the data in the collection

Collection collection =new ArrayList();
		collection.add("a");
		collection.add("b");
		collection.add("c");
		collection.add("d");
		//collection.remove("b"); 
		collection.clear();                             //清空集合
		System.out.println(collection.toString());		//删除指定元素

The effect is as follows:
Insert picture description here
4.
Whether boolean contains(Object o) contains

Collection collection =new ArrayList();
	collection.add("a");
	collection.add("b");
	collection.add("c");
	collection.add("d");
//collection.remove("b"); 
//collection.clear();                             
//清空集合
collection.contains("c");					
//判断是否包含某某
	System.out.println(collection.toString());		//删除指定元素

The effect is as follows:
returns true
5. boolean isEmpty()
determines whether the collection is empty, returns true if it is empty, returns false if it is not empty
6. int size()
outputs the length of the collection, several elements indicate several lengths

Fourth, the traversal of the collection is set to array traversal

In fact, it is to obtain each element in the collection in turn, and turn the collection into an array, which can realize the traversal of the collection.
Use the toArray() method. This method is not commonly used, but there is a way to switch here

public static void main(String[] args) {
    
    
		//demo1();
		Collection collection =new ArrayList();
		collection.add(new Student("张三",12));	
//Object obj = new Student("张三",12);父类引用指向子类
		collection.add(new Student("李四",13));
		collection.add(new Student("王五",14));
		Object[] arr =collection.toArray();		
//将集合转为数组
		
		for (int i = 0; i < arr.length; i++) {
    
    
			System.out.println(arr[i]);
			Student s =(Student)arr[i];         //向下转型
			System.out.println(s.getName());
//报错,因为存放在数组的时候,已经转换为Object[]数组,虽然存储了Student的对象,但是已经提升为Object
//这就是多态的弊端,不能使用子类特有的属性和行为。所以我们需要把Object数组中存储的Object类型的对象,
//向下转型。
		}
		
	}

	private static void demo1() {
    
    
		Collection collection = new ArrayList();
				collection.add("a");
				collection.add("b");
				collection.add("c");
				collection.add("d");
				Object[] arr =collection.toArray();			
//将集合转换为数组
				for (int i = 0; i < arr.length; i++) {
    
    
					System.out.print(arr[i]);
				}
	}

An error is reported, because when stored in an array, it has been converted to an Object[] array. Although the object of Student is stored, it has been upgraded to Object.
This is the drawback of polymorphism, and the unique properties and behaviors of the subclass cannot be used. So we need to cast the objects of type Object stored in the Object array //downward.

Five, the collection framework (Collection collection with All function test)

1. boolean addAll(Collection c)

Collection collection1 = new ArrayList();
				collection1.add("a");
				collection1.add("b");
				collection1.add("c");
		Collection collection2 = new ArrayList();
				collection2.add("d");
				collection2.add("e");
				collection2.add("f");
				collection1.addAll(collection2);
//如果我们写成了collection1.add(collection2);	
//此时会把集合2当成一个对象添加到集合1中
System.out.println(collection1); 				
//将集合2 放到集合1 中

The effect is as follows:
Insert picture description here
2. boolean removeAll(Collection c)
This method deletes the intersection between the two collections. If there is no intersection, it returns false and the deletion is unsuccessful.

Collection collection1 = new ArrayList();
	collection1.add("a");
	collection1.add("b");
	collection1.add("c");
Collection collection2 = new ArrayList();
	collection2.add("a");
	collection2.add("b");
	collection2.add("z");
boolean b = collection1.removeAll(collection2);
	System.out.println(b);
	System.out.println(collection1);

The effect is as follows:
Insert picture description here
3. boolean containsAll(Collection c)
determines whether the called collection contains the passed-in collection, if there are elements in the passed-in collection that are not in the calling collection, return false. Duplicate values ​​do not matter.

Collection collection1 = new ArrayList();
		collection1.add("a");
		collection1.add("b");
		collection1.add("c");
		Collection collection2 = new ArrayList();
		collection2.add("a");
		collection2.add("b");
		collection2.add("b");
		boolean b = collection1.removeAll(collection2);		
		//判断调用的集合是否包含传入的集合
		System.out.println(b);
		System.out.println(collection1);

The effect is as follows:
Insert picture description here
4. boolean retainAll(Collection c)
This method means to take the intersection between two collections and assign it to the called collection. If the called collection changes, it returns true, and if the called collection does not change, it returns false.

Collection collection1 = new ArrayList();
		collection1.add("a");
		collection1.add("b");
		collection1.add("c");
		Collection collection2 = new ArrayList();
		collection2.add("a");
		collection2.add("b");
		collection2.add("z");
		boolean b = collection1.retainAll(collection2);		//
		System.out.println(b);
		System.out.println(collection1);

The effect is as follows:
Insert picture description here

If collection2 and collection1 are the same, return false.

6. Iterator traversal of traversal of collection

Overview of Iterators
Collections are used to store elements. If the stored elements need to be viewed, then iteration (traversal) is required, and iteration is traversal

Collection collection1 =new ArrayList();
		collection1.add("a");
		collection1.add("b");
		collection1.add("c");
		//对集合的元素迭代(遍历)
		Iterator it =collection1.iterator(); 			
//获取迭代器
		boolean b1 = it.hasNext();					
//判断集合中是否有元素,有就返回false
		Object object1 =it.next();
		System.out.println(b1);
		System.out.println(object1);
		boolean b2 = it.hasNext();					
//判断集合中是否有元素,有就返回false
		Object object2 =it.next();					
//指针会向后移动一位
		System.out.println(b1);
		System.out.println(object2);

The effect is as follows:
Insert picture description here
this way to traverse the array is too cumbersome, so we try to combine the two methods

// TODO Auto-generated method stub
		Collection collection1 =new ArrayList();
		collection1.add("a");
		collection1.add("b");
		collection1.add("c");
		Iterator it =collection1.iterator();
		while (it.hasNext()) {
    
    
			System.out.println(it.next());
		}
}

The effect is as follows:
Insert picture description here
when we are storing an object, we want to obtain a certain attribute of the object, and the same requires a forced conversion

Collection collection1 =new ArrayList();
		collection1.add(new Student("张三",12));	
		collection1.add(new Student("李四",13));
		collection1.add(new Student("王五",14));
		//获取迭代器
		Iterator it =collection1.iterator();
		while (it.hasNext()) {
    
    
			System.out.println(it.next());
			Student student =(Student) it.next();
			System.out.println(student.getName()+student.getAge());
}

Seven, iterator principle

Principle of iterator: Iterator is to traverse the collection, and the internal storage structure of each collection is different, so the storage and retrieval of each collection are different, so you need to define hasNext() and in each class Next() method, this is possible, but it will make the entire collection system too bloated.The iterator extracts such a method upwards out of the interface, and then defines its own iteration method within each class. The advantages of this are Second, the first stipulates that the traversal methods of the entire collection system are the hasNext() and next() methods.Second, the code has the underlying internal implementation, and the user does not care how to implement it, but can use it.

Guess you like

Origin blog.csdn.net/Mr_GYF/article/details/108626398