当前位置: 代码迷 >> 综合 >> Java---Collection
  详细解决方案

Java---Collection

热度:96   发布时间:2023-10-21 18:08:34.0

Collection接口用于表示任何对象或元素组。想要尽可能以常规方式处理一组元素时,就使用这一接口。

Iterator接口主要用来枚举集合中的元素。 可理解成集合的查寻组件

组操作:Collection接口支持的其它操作,要么是作用于元素组的任务,要么是同时作用于整个集合的任务。

    boolean contains( Object obj )
    boolean addAll( Collection collection )    //取并集
    void clear()
    void removeAll( Collection collection )

    void retainAll( Collection collection )       //取交集


import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;import org.junit.Test;
/** Collection的功能由它实现类决定* 1. List允许重复,有序(先添加在前,后添加的元素位置在后)* 2. Set不允许重复,无序(跟添加的先后无关,只跟元素本身的hashCode值)* */
public class CollectionDemo {@Testpublic void demo1() {Collection col = new ArrayList();// 增col.add(100);col.add("Java");col.add(3.14);col.add(new Person("Jack", 22));col.add('a');System.out.println("size1:"+col.size());Collection col2 = new ArrayList();col2.add(1);col2.add(2);col2.add(3);col.addAll(col2);System.out.println("size2:"+col.size());// 删col.removeAll(col2);col.remove(3.14);// 查Iterator it = col.iterator();while (it.hasNext()) {Object obj = it.next();if(obj instanceof Person){System.out.println("人:"+obj);}else{System.out.println(obj);}}}@Test//Collection的功能由实现类决定public void demo2() {//Collection col = new ArrayList(); //List允许重复,有序(先添加在前)Collection col = new HashSet(); //Set不允许重复,无序(跟添加的先后无关,只跟元素本身的hashCode值)// 增col.add(100);col.add(100);col.add("Java");col.add(3.14);col.add(200);col.add(new Person("Jack", 22));col.add('a');// 改1--位置变了(对List来说,对Set不影响)col.remove(200);col.add(300);// 改2--位置不变(对List来说,对Set不影响)
//		Object objs[] = col.toArray();
//		col.clear();
//		for(int i=0;i<objs.length;i++){
//			if(objs[i].equals(200)){
//				objs[i]=300;
//			}
//			col.add(objs[i]);
//		}// 查Iterator it = col.iterator();while (it.hasNext()) {Object obj = it.next();System.out.println(obj);}}
}

Person类:

class Person {private String name;private int age;public Person(String name, int age) {this.name = name;this.age = 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;}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + age;result = prime * result + ((name == null) ? 0 : name.hashCode());return result;}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;Person other = (Person) obj;if (age != other.age)return false;if (name == null) {if (other.name != null)return false;} else if (!name.equals(other.name))return false;return true;}@Overridepublic String toString() {return name + "," + age;}}