对象实例的比较要用equals!!
一定要密切注意for循环的范围!!!
重写的equals
public boolean equals(ArrayList names)
{
if(this.next==names.next)
{
for(int i=0;i<this.next;i++)
{
if(this.list[i].equals(names.list[i])){
}
else{
return false;
}
}
return true;}
else{
out.println("两个访问量不同!");
return false;}
}
完整代码
package cc.openhome;
import java.util.Arrays;
import java.util.Scanner;
import static java.lang.System.out;
public class ArrayList {
private Object[] list;
private int next=0;
public ArrayList(int capacity){//指定初始容量
list= new Object[capacity];
}
public ArrayList(){//初始容量默认为16
this(16);
}
public void add(Object o){//收集对象方法
if(next==list.length){//自动增长Object数组长度
list=Arrays.copyOf(list,list.length*2);
}
list[next++]=o;
}
public Object get(int index){//索引取得收集的对象
return list[index];
}
public int size(){//已收集的对象个数
return next;
}
public boolean equals(ArrayList names)
{
if(this.next==names.next)
{
for(int i=0;i<this.next;i++)
{
if(this.list[i].equals(names.list[i])){
}
else{
return false;
}
}
return true;}
else{
out.println("两个访问量不同!");
return false;}
}
static void collectNameTo(ArrayList names){
Scanner console = new Scanner(System.in);
while(true){
out.print("访客名称:");
String name =console.nextLine();
if(name.equals("quit")){
break;
}
names.add(name);
}
}
static void printUpperCase(ArrayList names) {
for(int i = 0; i < names.size(); i++) {
String name = (String) names.get(i);
out.println(name.toUpperCase());
}
}
public static void main(String[] args) {
ArrayList names=new ArrayList();
collectNameTo(names);
out.println("访客名单");
printUpperCase(names);
ArrayList name1=new ArrayList();
collectNameTo(name1);
out.println("访客名单");
printUpperCase(name1);
System.out.println(names.equals(name1));
}
}
本文深入探讨了自定义ArrayList类的实现,包括对象收集、数组自动增长、获取对象及大小等功能。重点讲解了equals方法的正确使用,通过比较两个ArrayList实例中元素的等价性来判断对象是否相等,而非简单引用比较。
1952

被折叠的 条评论
为什么被折叠?



