java集合中“享元”体现的分享

本文深入探讨了Java集合框架中享元模式的实现,通过具体案例CountingIntegerList展示了如何利用AbstractList创建只读List,重点介绍了get()和size()方法的作用,以及它们在迭代器实现中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java集合享元的解决方案

为了从AbstractList创建只读的的List,必须实现get()和size()

package SourceCode;

import java.util.AbstractList;

public class CountingIntegerList extends AbstractList<Integer>{
	private int size;
	public CountingIntegerList(int size){
		this.size = size;
	}
	public Integer get(int index){
		return Integer.valueOf(index);
	}
	public int size(){return size;}
	public static void main(String[] args) {
		System.out.println(new CountingIntegerList(10));
	}
}

执行结果:
在这里插入图片描述
当寻找List中的值时,get()将产生它,因此这个List实际上并不必组装。

剖析源码

查看AbstractList源码看其迭代器(iterator)的实现

public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E>

这里使用到get()和size()获得List对象的存储值,获得的迭代器就可以List中的值了

    public Iterator<E> iterator() {
        return new Itr();
    }

    private class Itr implements Iterator<E> {
        /**
         * Index of element to be returned by subsequent call to next.
         */
        int cursor = 0;

        /**
         * Index of element returned by most recent call to next or
         * previous.  Reset to -1 if this element is deleted by a call
         * to remove.
         */
        int lastRet = -1;

        /**
         * The modCount value that the iterator believes that the backing
         * List should have.  If this expectation is violated, the iterator
         * has detected concurrent modification.
         */
        int expectedModCount = modCount;

        public boolean hasNext() {
            return cursor != size();
        }

        public E next() {
            checkForComodification();
            try {
                int i = cursor;
                E next = get(i);
                lastRet = i;
                cursor = i + 1;
                return next;
            } catch (IndexOutOfBoundsException e) {
                checkForComodification();
                throw new NoSuchElementException();
            }
        }

配合AbstractCollection中对toString()来打印出List中所有的值.

    public String toString() {
        Iterator<E> it = iterator();
        if (! it.hasNext())
            return "[]";

        StringBuilder sb = new StringBuilder();
        sb.append('[');
        for (;;) {
            E e = it.next();
            sb.append(e == this ? "(this Collection)" : e);
            if (! it.hasNext())
                return sb.append(']').toString();
            sb.append(',').append(' ');
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值