collection

xiaoxiao2025-12-30  4

[code="java"]马士兵 ___第七章__容器 学习笔记[/code] [code] package com.testcollection; import java.util.ArrayList; import java.util.Collection ; //collection 接口的测试 //练习遍历容器 Iterator public class TestCollection { public static void main(String args[]) { // 接口引用指向具体实现类的对象,为实现多态打下了坚实的基础 // 我们可以将new ArrayList()改成new LinkedList()等等,而不需要改动该程序中的其他部分 // 极大地提高了可扩充性,多态的作用也明显表现了出来 Collection c = new ArrayList() ; c.add("hello") ; c.add(new Integer(100)) ; c.add(new Name("f1","l1")) ; c.add(new Name("f2","22")) ; // c.remove("hello") ; // Iterator i = c.iterator(); // while(i.hasNext()) { // Name n = (Name)i.next() ; // System.out.println(n.getFirstName()) ; // } System.out.println(c.size()) ; // 这3个类(String、Name、Integer)都已经重写了Object类的toString方法 // 打印接口引用c,实际上是分别调用这个接口中各个对象的toString方法 System.out.println(c) ; System.out.println("下面测试remove") ; System.out.println(c.remove("hello")) ; //true System.out.println(c.remove(new Integer(100))) ;//true System.out.println(c.remove(new Name("f1","l1"))) ; //false 当Name的类中没有覆写equals方法时为FALSE //上面为false 的原因:此处新new 出来的对象,删除时比较的是equals方法,而Name类中未重写 //equals方法,而String和Integer 这两个类已经实现了equals方法 } } class Name{ private String firstName, secondName ; Name(String firstName, String secondName) { this.firstName = firstName ; this.secondName = secondName ; } public String toString(){ return firstName + " " + secondName ; } public String getFirstName() { return firstName ; } public String getSecondName() { return secondName; } public boolean equals (Object obj) { if(obj instanceof Name) { Name n = (Name) obj ; //比较这两个对象的内容是否一致 if (this.firstName.equals(n.firstName) && this.secondName.equals(n.secondName)) return true; else return false; }else { //交给Name的父类去处理(其父类是object类,比较equals就相当于还是比较=) return super.equals(obj) ; } } public int hashcode() { return this.firstName.hashCode() ; } } [/code] [code] list :有序可重复; set: 无序不可重复; 重写equals方法,应该也重写hashCode 方法。两个对象若 equals的话,则两个对象的hascode 相等。 hashCode 多做索引时使用; [/code]
转载请注明原文地址: https://www.6miu.com/read-5041772.html

最新回复(0)