首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Collection 施用举例1

2012-12-28 
Collection 使用举例1?Collection 使用举例?容器类对象在调用remove,Collection 等方法时需要比较对象是否

Collection 使用举例1

?

Collection 使用举例

?

容器类对象在调用remove,Collection 等方法时需要比较对象是否相等,这回涉及到对象类型的equals方法和hashCode方法,对于自定义的的类型
//需要重写equals和hashCode方法以实现自定义的对象相等规则。

package com.study;import java.util.*;public class CollectionDemo02 {public static void main(String []args) {Collection c1= new LinkedList();c1.add("CollectionDemo02");c1.add("CollectionDemo02");c1.add("CollectionDemo02");c1.add("CollectionDemo02");c1.add("TestCollection");c1.add(new Integer(100));c1.add(new Double(100.22));c1.add(new Boolean(true));c1.add(new Boolean(false));c1.add(new Desk("Office Desk 1","100","200"));c1.add(new Desk("Office Desk 2","200","400"));c1.add(new Desk("Office Desk 3","300","600"));Collection c2 = new ArrayList();c2.add(c1);c2.add("zhudansheng test Collection");System.out.println("==============================");System.out.println(c1);//c1全部打印出来System.out.println("==============================");System.out.println(c2);//把c1和c2数据全部打印出来System.out.println("==============================");c2.remove("TestCollection");//为什么删除不掉呢?c2.remove("CollectionDemo02");//为什么删除不掉呢?c2.remove(new Boolean(false));//为什么删除不掉呢?System.out.println(c2);System.out.println("==============================");//因为ColleciontDemo02有好几条数据所以当前只可以删除最后的一条数据System.out.println("==============================");System.out.println(c1);System.out.println("==============================");c1.remove("TestCollection");c1.remove("CollectionDemo02"); c1.remove("CollectionDemo02"); c1.remove("CollectionDemo02"); System.out.println(c1);System.out.println("==============================");//备注:容器类对象在调用remove,Collection 等方法时需要比较对象是否相等,这回涉及到对象类型的equals方法和hashCode方法,对于自定义的的类型//需要重写equals和hashCode方法以实现自定义的对象相等规则。System.out.println(c1.remove(new Desk("Office Desk 1","100","200")));//false }}class Desk {private String name;private String width;private String height;public Desk(String name,String width,String height) {this.name=name;this.width=width;this.height=height;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getWidth() {return width;}public void setWidth(String width) {this.width = width;}public String getHeight() {return height;}public void setHeight(String height) {this.height = height;} }

?

热点排行