注册 登录
编程论坛 JAVA论坛

一个链表应用的问题

X15810803158 发布于 2016-12-25 21:03, 1647 次点击

package mypro01;

class Book{//定义一个图书类
    private String name;//书名
    private double price;//价钱
    public Book(String name,double price){
        this.name = name;
        this.price = price;
    }
    public String getInfo(){
        return "书名"+this.name+" ,书价格"+this.price;
    }
    //比较两个对象
    public boolean compara(Book book){
        if(book == null){
            return false;
        }
        if(this == book){
            return true;
        }
        if(this.name.equals(book.name) && this.price == book.price ){
            return true;
        }else{
            return false;
        }
    }
   
   
   
}

class Link{//定义一个链表类
    private class Node{
        private Book date;
        private Node next;
        public Node(Book date){
            this.date = this.date;
        }
        public void addNode(Node newNode){
            if(this.next == null){
                this.next = newNode;
            }else{
                this.next.addNode(newNode);
            }
        }
        
        public boolean containsNode(Book date){
            if((this.date)){
                return true;
            }else{
                if(this.next == null){
                return false;
            }
                else{
                    return this.next.containsNode(date);
                            }
                }
        }//以上是内部类
    }
    private Node root;//根节点
    private int count = 0;//个数
    //增加数据
    public void add(Book date){
        Node newNode = new Node(date);
        if(this.root == null){//根节点为空
            this.root = newNode;
        }else{
            this.root.addNode(newNode);
        }
        count++;
    }
    //返回个数
    public int size(){
        return this.count;
    }
    //判断是否包含数据
    public boolean contains (Book date){
        if(date == null && this.root == null){
            return false;
        }else{
            return this.root.containsNode(date);
        }
    }
   
}

public class LinkDe {
   
    public static void main(String[] args){
        Link a = new Link();
        a.add(new Book("java",34.2));
        a.add(new Book("c",23.1));
        System.out.println(a.size());
        System.out.println(a.contains(new Book("java",34.2)))    ;
    }

}
3 回复
#2
X158108031582016-12-25 21:05
只有本站会员才能查看附件,请 登录
#3
X158108031582016-12-25 21:06
为什么打印的是false??
#4
crf12052016-12-25 21:35
原因很简单,你新建了两个对象,new Book("JAVA",34.2),你写两次,就表示你创建了两个对象,每个对象的属性都是一样的,但是在内存中的地址是不同的。
1