shawn.bug 2009-04-25 21:52
浏览 210
已采纳

自己写个链表,查找有点问题。

class MyList{
private Object[] data;
private int index=0;
public MyList(int size){
data=new Object[size];
}
private void expand(){
Object[] data2=new Object[data.length*2];
System.arraycopy(data,0,data2,0,data.length);
data=data2;
}
public void add(Object o){
if (data.length==index) expand();
data[index]=o;
index++;
}
public void add(int pos,Object o){
if (data.length==index) expand();
for(int i=index;i>pos;i--){
data[i]=data[i-1];
}
data[pos]=o;
index++;
}
public void change(int pos,Object o){
data[pos]=o;
}
public Object remove(int pos){
Object o=data[pos];
index--;
for(int i=pos;i<index;i++){
data[i]=data[i+1];
}
return o;
}
public int size(){
return index;
}
public Object get(int pos){
return data[pos];
}
public void clear(){
index=0;
}
public boolean isEmpty(){
return index==0;
}
public Object[] toArray(){
return data;
}
}

public class ListTest {
private static MyList list ;
/*
* 判断内存是否存在
*/
public static boolean findMemory(int a){
String s=Integer.toString(a);

    for(int i=0;i<list.size();i++){
        Object o=list.get(i);
        if (o.equals(s)){  [color=red]//内容判断根本不对,不知道错在哪里?一直都是不相等,怎么判断能相等?[/color]
            return true;
        }
    }
        return false;
}

public static void disPlay(){
for(int i=list.size()-1;i>=0;i-- ){
Object o=list.get(i);
System.out.println(i+" "+o);
}
}

public static void main(String[] args) throws IOException {
    /*
     * 创建内存
     */
    System.out.print("输入内存块数>");
    int memory_i=Util.keyReadInt();
    list=new MyList(memory_i);

    for(int i=0;i<memory_i;i++){
        list.add("null");
    }


//  disPlay();
    list.change(2, 2);
    System.out.println("========");
//  disPlay();
    System.out.println(findMemory(2));   [color=red][color=darkred]//返回值始终是假,怎么一直没找到?[/color][/color]
}

}
[b]问题补充:[/b]
lovewhzlq 你说的方法我也试了,不转的话也不行啊?
为什么啊?怎么改?

  • 写回答

1条回答 默认 最新

  • wanghaolovezlq 2009-04-25 22:28
    关注

    public static boolean findMemory(int a){
    [color=red]String[/color] s=Integer.toString(a); //[color=red]你把整型的转换成字符串了,[/color]

    for(int i=0;i<list.size();i++){
    Object o=list.get(i);
    if (o.equals(s)){ //内容判断根本不对,不知道错在哪里?一直都是不相等,怎么判断能相等?
    return true;
    }

    list.change(2, 2);
    这句的意思就是给位置2的赋值为2嘛,[color=red]2被自动装箱成是Integer类型嘛,[/color]

    注意看红色部分,Integer类型和String类型的用equals当然永远也不相等

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 html5+css有人可以帮吗?
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?