Collection接口

来源:互联网 发布:linux 启动原理 编辑:程序博客网 时间:2024/04/30 06:52

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


package cn.hncu.collection;


import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;


public class CollectionDemo {
@SuppressWarnings("rawtypes")
public static void main(String[] args) {
Collection col=new ArrayList();
//col=new HashSet();//因为用hash..等类时,是没有排序的,地址和内存是随机开的,不知道位置,要想有固定的输出格式,必须写hashCode方法(调用toString 是调用hash值),所加入元素的存储位置是由各元素的hashCode值来定的。当Perosn类不覆盖hashCode时,person对象的位置是不定,因此这样它的hashCode是对象的内存地址。
//综上,想当对象的位置确定,则需要覆盖hashCode()方式
//增
col.add(1);
col.add(4);
col.add(4);//如果用Set...方法不允许从复,因为调用时是编译时运行
col.add("41");
col.add("aa");
col.add(new Person("张三", 20));
col.add(new Person("Jack", 20));
col.add(new Person("Li", 20));

//删
// col.remove(1);

//改
Object objs[]=col.toArray();
for(Object obj:objs){
if(obj instanceof Person){
((Person) obj).setAge(100);
}
//// col.add(3);//不能写入
// System.out.println(obj);
}

//查
Iterator it=col.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}

}

package cn.hncu.collection;
 class Person {
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;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Person() {
super();
}
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + age;
// result = prime * result + ((name == null) ? 0 : name.hashCode());
// return result;
// }
// @Override
// public 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;
// }
//
}

0 0
原创粉丝点击