微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

对象引用等于检查 LRU 缓存实现

如何解决对象引用等于检查 LRU 缓存实现

我对 Java 的 equals 的理解是,如果两个对象具有相同的引用,则它们通过 == 相等。例如,如果是字符串,则需要使用 .equals() 来比较值;

下面的代码一个示例 LRUCache。在 addToEnd 方法中,有一次我将尾部与节点进行比较(它表示什么都不做),即使它们具有相同的引用,它们也不会命中该代码块。有人可以解释为什么吗?调试时,它们具有完全相同的引用。

public class LRUCache {

    private class Node {
        private int key;
        private int value;
        private Node prev;
        private Node next;

        private Node (int key,int value) {
            this.key = key;
            this.value = value;
        }
    }

    private Map<Integer,Node> lookup;
    private int capacity;
    private int size;
    private Node head;
    private Node tail;

    public LRUCache(int capacity) {
        this.capacity = capacity;
        this.lookup = new HashMap<Integer,Node>();
    }

    private void addToEnd(Node node) {
        if (node == this.tail) {
            //do nothing
        }
        if (this.tail != null) {
            if (node == this.head) {
                this.head = this.head.next;
            }
            Node prev = node.prev;
            Node next = node.next;
            if (prev != null) {
                prev.next = next;
            }

            if (next != null) {
                next.prev = prev;
            }
            this.tail.next = node;
            node.prev = this.tail;
            node.next = null;
            this.tail = node;
        } else {
            this.head = node;
            this.tail = this.head;
        }
    }

    private void popHead() {
        if (this.head != null) {
            this.lookup.remove(this.head.key);
            Node node = this.head.next;
            this.head = node;
            this.size--;
        }
    }

    public int get(int key) {
        if (lookup.containsKey(key)) {
            Node node = lookup.get(key);
            addToEnd(node);
            return node.value;
        } else {
            return -1;
        }
    }

    public void put(int key,int value) {
        if (lookup.containsKey(key)) {
            Node node = lookup.get(key);
            addToEnd(node);
            node.value = value;
            return;
        } else if (this.size == this.capacity) {
            popHead();
        }
        Node newNode = new Node(key,value);
        addToEnd(newNode);
        this.lookup.put(key,newNode);
        this.size++;
    }
}

这是我运行的代码

       LRUCache lRUCache = new LRUCache(1);
       lRUCache.put(2,1);
       lRUCache.get(2); 
       lRUCache.put(3,2); 
       System.out.println(lRUCache.get(2)); //getting 1 but should be -1
       System.out.println(lRUCache.get(3));

解决方法

        if (node == this.tail) {
            //do nothing
        }

意图可能是什么都不做然后返回

缺少 return 关键字。

所以,添加 return 应该给出正确的行为

        if (node == this.tail) {
            return;
        }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。