Модераторы: SoWa
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Collections, Java like Collections 
:(
    Опции темы
AntonioBanderaz
Дата 28.10.2006, 14:53 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Velichko Anton
**


Профиль
Группа: Участник
Сообщений: 851
Регистрация: 28.4.2005
Где: Санкт-Петербург

Репутация: 9
Всего: 18



Задача сдлать java like collections на AS

Нужен интерфейс коллекции создаём
Код

package com.avelichko.lang.util
{
    public interface Collection
    {
        /**
         * Returns the number of elements in this collection. 
         * 
         * @return the number of elements in this collection
         */
         
         function size():int;
         
         /**
         * Returns <tt>true</tt> if this collection contains no elements.
         *
         * @return <tt>true</tt> if this collection contains no elements
         */
         function isEmpty():Boolean;
         
         /**
         * Returns <tt>true</tt> if this collection contains the specified
         * element.  More formally, returns <tt>true</tt> if and only if this
         * collection contains at least one element <tt>e</tt> such that
         * <tt>(o==null ? e==null : o.equals(e))</tt>.
         *
         * @param o element whose presence in this collection is to be tested.
         * @return <tt>true</tt> if this collection contains the specified
         *         element
         * @throws NullPointerException if the specified element is null and this
         *         collection does not support null elements (optional).
         */
         function contains(o:Object):Boolean;
         
         /**
         * Returns an iterator over the elements in this collection.  There are no
         * guarantees concerning the order in which the elements are returned
         * (unless this collection is an instance of some class that provides a
         * guarantee).
         * 
         * @return an <tt>Iterator</tt> over the elements in this collection
         */
         function iterator():Iterator;
         
         /**
         * Returns an array containing all of the elements in this collection.  If
         * the collection makes any guarantees as to what order its elements are
         * returned by its iterator, this method must return the elements in the
         * same order.<p>
         *
         * The returned array will be "safe" in that no references to it are
         * maintained by this collection.  (In other words, this method must
         * allocate a new array even if this collection is backed by an array).
         * The caller is thus free to modify the returned array.<p>
         *
         * This method acts as bridge between array-based and collection-based
         * APIs.
         *
         * @return an array containing all of the elements in this collection
         */
         function toArray():Array;
         
         /**
         * Ensures that this collection contains the specified element (optional
         * operation).  Returns <tt>true</tt> if this collection changed as a
         * result of the call.  (Returns <tt>false</tt> if this collection does
         * not permit duplicates and already contains the specified element.)<p>
         *
         * Collections that support this operation may place limitations on what
         * elements may be added to this collection.  In particular, some
         * collections will refuse to add <tt>null</tt> elements, and others will
         * impose restrictions on the type of elements that may be added.
         * Collection classes should clearly specify in their documentation any
         * restrictions on what elements may be added.<p>
         *
         * If a collection refuses to add a particular element for any reason
         * other than that it already contains the element, it <i>must</i> throw
         * an exception (rather than returning <tt>false</tt>).  This preserves
         * the invariant that a collection always contains the specified element
         * after this call returns.
         *
         * @param o element whose presence in this collection is to be ensured.
         * @return <tt>true</tt> if this collection changed as a result of the
         *         call
         * 
         * @throws UnsupportedOperationException <tt>add</tt> is not supported by
         *         this collection.
         * @throws NullPointerException if the specified element is null and this
         *         collection does not support null elements.
         */
         function add(o:Object):Boolean;
         
         /**
         * Removes a single instance of the specified element from this
         * collection, if it is present (optional operation). If this collection contains one or more such
         * elements.  Returns true if this collection contained the specified
         * element (or equivalently, if this collection changed as a result of the
         * call).
         *
         * @param o element to be removed from this collection, if present.
         * @return <tt>true</tt> if this collection changed as a result of the
         *         call
         * 
         * @throws NullPointerException if the specified element is null and this
         *         collection does not support null elements (optional).
         * @throws UnsupportedOperationException remove is not supported by this
         *         collection.
         */
         function remove(o:Object):Boolean;
         
         /**
         * Removes all of the elements from this collection (optional operation).
         * This collection will be empty after this method returns unless it
         * throws an exception.
         *
         * @throws UnsupportedOperationException if the <tt>clear</tt> method is
         *         not supported by this collection.
         */
         function clear():void;
         
         /**
         * Returns the element at the specified position in this list.
         *
         * @param index index of element to return.
         * @return the element at the specified position in this list.
         * 
         * @throws IndexOutOfBoundsException if the index is out of range (index
         *          &lt; 0 || index &gt;= size()).
         */
        function get(index:int):Object;
        
        /**
        * Replaces the element at the specified position in this list with the
        * specified element (optional operation).
        *
        * @param index index of element to replace.
        * @param element element to be stored at the specified position.
        * @return the element previously at the specified position.
        * 
        * @throws UnsupportedOperationException if the <tt>set</tt> method is not
        *          supported by this list.
        * @throws NullPointerException if the specified element is null and
        *        this list does not support null elements.
        * @throws IndexOutOfBoundsException if the index is out of range
        *          (index &lt; 0 || index &gt;= size()).
        */
        function set(index:int, element:Object):Object;
        
        /**
        * Returns the index in this list of the first occurrence of the specified
        * element, or -1 if this list does not contain this element.
        * More formally, returns the lowest index <tt>i</tt> such that
        * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
        * or -1 if there is no such index.
        *
        * @param o element to search for.
        * @return the index in this list of the first occurrence of the specified
        *           element, or -1 if this list does not contain this element.
        * @throws NullPointerException if the specified element is null and this
        *         list does not support null elements (optional).
        */
        function indexOf(o:Object):int;
    }
}


Теперь надо создать классы всех исключений, унаследовав их от Error
Код

package com.avelichko.lang.util.exceptions
{
    public class IndexOutOfBoundsException extends Error
    {
        public function IndexOutOfBoundsException(message:String = "", id:int = 0)
        {
            super(message, id);
        }
        
    }
}

package com.avelichko.lang.util.exceptions
{
    public class NoSuchElementException extends Error
    {
        public function NoSuchElementException(message:String="", id:int=0)
        {
            super(message, id);
        }
        
    }
}

package com.avelichko.lang.util.exceptions
{
    public class NullPointerException extends Error
    {
        public function NullPointerException(message:String="", id:int=0)
        {
            super(message, id);
        }
        
    }
}

package com.avelichko.lang.util.exceptions
{
    public class UnsupportedOperationException extends Error
    {
        public function UnsupportedOperationException(message:String="", id:int=0)
        {
            super(message, id);
        }
        
    }
}


Теперь делаем интерфейс итератора
Код

package com.avelichko.lang.util
{
    public interface Iterator {
        /**
         * Returns <tt>true</tt> if the iteration has more elements. (In other
         * words, returns <tt>true</tt> if <tt>next</tt> would return an element
         * rather than throwing an exception.)
         *
         * @return <tt>true</tt> if the iterator has more elements.
         */
        function hasNext():Boolean;
    
        /**
         * Returns the next element in the iteration.
         *
         * @return the next element in the iteration.
         * @exception NoSuchElementException iteration has no more elements.
         */
        function next():Object;
    
        /**
         * 
         * Removes from the underlying collection the last element returned by the
         * iterator (optional operation).  This method can be called only once per
         * call to <tt>next</tt>.  The behavior of an iterator is unspecified if
         * the underlying collection is modified while the iteration is in
         * progress in any way other than by calling this method.
         *
         */
        function remove():void;
    }
}


Теперь надо сделать некий базовый класс для нашей коллекции например AbstractCollection, делаем
Код

package com.avelichko.lang.util
{
    import com.avelichko.lang.util.exceptions.IndexOutOfBoundsException;
    import com.avelichko.lang.util.exceptions.NullPointerException;
    
    public dynamic class AbstractCollection implements Collection
    {
        protected var collection:Array = new Array();
        
        public function AbstractCollection() {
            collection = new Array();
        }
        
        public function contains(o:Object):Boolean
        {
            var e:Iterator = iterator();
            while (e.hasNext())
                if (e.next() == o)
                    return true;
            return false;
        }
        
        public function toArray():Array
        {
            var result:Array = new Array(size());
            var e:Iterator = iterator();
            while(e.hasNext())
                result.push(e.next());
            return result;
        }
        
        public function isEmpty():Boolean
        {
            return size() == 0;
        }
        
        public function remove(o:Object):Boolean
        {
            var e:Iterator = iterator();
            while (e.hasNext()) {
                if (o == e.next()) {
                    e.remove();
                    return true;
                }
            }
            return false;
        }
        
        public function clear():void
        {
            var e:Iterator = iterator();
            while (e.hasNext()) {
                e.next();
                e.remove();
            }
        }
        
        public function iterator():Iterator
        {
            return new ArrayIterator(collection);
        }
        
        public function add(o:Object):Boolean
        {
            return collection.push(o) > 0;
        }
        
        public function size():int
        {
            return collection.length;
        }
        
        public function get(index:int):Object {
            if(index < 0 || index >= size()) throw new IndexOutOfBoundsException("Index out of range [0:" + size().toString() + "]");
            return collection[index];
        }
        
        public function set(index:int, element:Object):Object {
            if(index < 0 || index >= size()) throw new IndexOutOfBoundsException("Index out of range [0:" + size().toString() + "]");
            if(element == null) throw new NullPointerException("Element must be not null");
            collection[index] = element;
            if(index == 0) return null;
            return collection[index - 1];
        }
        
        
        public function indexOf(o:Object):int {
            if(o == null) throw new NullPointerException("Element must be not null");
            return collection.indexOf(o);
        }
    }
}


Сделали, ну а теперь на его основе сделаем например ArrayList
Код

package com.avelichko.lang.util
{
    import com.avelichko.lang.util.exceptions.IndexOutOfBoundsException;
    
    public class ArrayList extends AbstractCollection
    {
        public function ArrayList()
        {
            super();
        }
        
        public override function set(index:int, element:Object):Object {
            if(index < 0 || index >= size()) throw new IndexOutOfBoundsException("Index out of range [0:" + size().toString() + "]");
            //if(element == null) throw new NullPointerException("Element must be not null");
            collection[index] = element;
            if(index == 0) return null;
            return collection[index - 1];
        }
        
        public override function indexOf(o:Object):int {
            //if(element == null) throw new NullPointerException("Element must be not null");
            return collection.indexOf(o);
        }
    }
}


теперь бин итератора назовём его например ArrayIterator
Код

package com.avelichko.lang.util
{
    import com.avelichko.lang.util.exceptions.NullPointerException;
    import com.avelichko.lang.util.exceptions.NoSuchElementException;
    
    public class ArrayIterator implements Iterator
    {
        private var index:uint = 0;
        private var source:Array = null;
        
        public function ArrayIterator(array:Array) {
            if(array == null) throw new NullPointerException("TargerArray must be not null");
            index = 0;
            source = array;
        }
        
        public function remove():void
        {
            source.splice(index - 1, 1);
        }
        
        public function hasNext():Boolean
        {
            return index < source.length;
        }
        
        public function next():Object
        {
            if(!hasNext()) throw new NoSuchElementException("No such element in collection");
            return source[index++];
        }
        
    }
}


собственно всё.... Теперь как этим пользоваться
Код

package {
    import flash.display.Sprite;
    import com.avelichko.lang.util.ArrayList;
    import com.avelichko.lang.util.Iterator;
    import flash.text.TextField;

    public class util extends Sprite
    {
        public function util()
        {
            var al:ArrayList = new ArrayList();
            al.add("bla bla");
            al.add("bla bla1");
            al.add("bla bla2");
            al.add("bla bla3");
            al.add("bla bla4");
            
            trace(al.size());
            var debug:TextField = new TextField();
            debug.border = true;
            debug.width = 200;
            debug.height = 200;
            
            debug.appendText("\r\n" + al.size().toString());
            var it:Iterator = al.iterator();
            while(it.hasNext()) {
                var str:String = it.next().toString();
                debug.appendText("\r\n" + str);
                trace(str);
                if(!it.hasNext()) { //Удалим-ка последний )
                    it.remove();
                }
            }
            trace(al.size());
            debug.appendText("\r\n" + al.size().toString());
            this.addChild(debug);
        }
    }
}


Что у нас на выходе
Код

5
bla bla
bla bla1
bla bla2
bla bla3
bla bla4
4
[SWF] C:\Documents and Settings\avelichko\My Documents\Flex Builder 2\util\bin\util-debug.swf - 7 473 bytes after decompression



--------------------
ГЫ... 
PM MAIL ICQ   Вверх
AntonioBanderaz
Дата 30.10.2006, 11:50 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Velichko Anton
**


Профиль
Группа: Участник
Сообщений: 851
Регистрация: 28.4.2005
Где: Санкт-Петербург

Репутация: 9
Всего: 18



Поехали дальше, хотим HashMap, пожалуйста

Интерфейс для мапы 
Код

package com.avelichko.lang.util
{
    public interface Map
    {
        function getEntry(key:Object):Object;
        
        function put(key:Object, value:Object):void;
        
        function contains(key:Object):Boolean;
        
        function putAll(map:Map):void;
        
        function entryList():Collection;
        
        function keyList():Collection;
        
        function size():int;
    }
}

AbstractMap.as
Код

package com.avelichko.lang.util
{
    import com.avelichko.lang.util.Map;
    import com.avelichko.lang.util.exceptions.NullPointerException;
    import com.avelichko.lang.util.exceptions.UnsupportedOperationException;

    public class AbstractMap implements Map
    {
        protected var eList:ArrayList = new ArrayList();
        protected var kList:ArrayList = new ArrayList();
        
        public function getEntry(key:Object):Object
        {
            var it:Iterator = eList.iterator();
            while(it.hasNext()) {
                var entry:MapEntry = it.next().valueOf();
                if(entry.equals(key)) {
                    return entry.val;
                    break;
                }
            }
            return null;
        }
        
        public function putAll(map:Map):void
        {
            var entrys:Collection = map.entryList();
            var it:Iterator = entrys.iterator();
            while(it.hasNext()) {
                var entry:MapEntry = it.next().valueOf();
                put(entry.key, entry.val);
            }
        }
        
        public function contains(key:Object):Boolean
        {
            var it:Iterator = eList.iterator();
            while(it.hasNext()) {
                var entry:MapEntry = it.next().valueOf();
                if(entry.equals(key)) {
                    return true;
                    break;
                }
            }
            return false;
        }
        
        public function keyList():Collection
        {
            if(kList.isEmpty()) {
                var it:Iterator = eList.iterator();
                while(it.hasNext()) {
                    var entry:MapEntry = it.next().valueOf();
                    kList.add(entry.key);
                }
            } 
            return kList;
        }
        
        public function entryList():Collection
        {
            return eList;
        }
        
        public function put(key:Object, value:Object):void
        {
            if(key == null) throw new NullPointerException("Key must be not null");
            var entry:MapEntry = new MapEntry();
            entry.key = key;
            entry.val = value;
            if(eList.add(entry)) {
                kList = new ArrayList();
                return;
            } throw new UnsupportedOperationException("Object does not putted");
        }
        
        public function size():int {
            return eList.size();
        }
        
    }
}


MapEntry.as
Код

package com.avelichko.lang.util
{
    import com.avelichko.lang.util.exceptions.NullPointerException;
    
    public class MapEntry {
        private var _key:Object = null;
        internal var _val:Object = null;
        
        public function get key():Object {
            return _key;
        }
        
        public function set key(o:Object):void {
            if(o == null) throw new NullPointerException("Key must be not null");
            _key = o;
        }
        
        public function get val():Object {
            return _val;
        }
        
        public function set val(o:Object):void {
            if(o == null ) throw new NullPointerException("Val must be not null");
            _val = o;
        }
        
        public function equals(o:Object):Boolean {
            return o == _key;
        }
    }
}


Собственно HashMap.as
Код

package com.avelichko.lang.util
{
    import com.avelichko.lang.util.exceptions.NullPointerException;
    import com.avelichko.lang.util.exceptions.UnsupportedOperationException;
    
    public class HashMap extends AbstractMap
    {
        public function HashMap()
        {
            super();
        }
        
        public override function put(key:Object, value:Object):void
        {
            if(key == null) throw new NullPointerException("Key must be not null");
            var entry:MapEntry = new MapEntry();
            if(contains(key)) {
                var it:Iterator = eList.iterator();
                while(it.hasNext()) {
                    entry = it.next().valueOf();
                    if(entry.equals(key)) {
                        it.remove();
                    }
                }
            }
            entry.key = key;
            entry.val = value;
            if(eList.add(entry)) {
                kList = new ArrayList();
                return;
            } throw new UnsupportedOperationException("Object does not putted");
        }        
    }
}


ЗЫ: как такового хеша здесь нет... просто назвал как в java. 

OOP в as полное [censored34! Пожалуйста, соблюдайте элементарные правила приличия при общении на форуме], чтобы прикастить к типу надо valueOf() делать... (((((

Это сообщение отредактировал(а) AntonioBanderaz - 30.10.2006, 11:51


--------------------
ГЫ... 
PM MAIL ICQ   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | ActionScript 3 | Следующая тема »


 




[ Время генерации скрипта: 0.0902 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.