Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
I am learning GoF Java Design Patterns and I want to see some real life examples of them. Can you guys point to some good usage of these Design Patterns.(preferably in Java's core libraries). Thank you
Does anyone have any idea, why removeRange method in AbstractList (and also in ArrayList) is protected? It looks like a quite well-defined and useful operation, but still, to use it, we're forced to subclass the List implementation. Is there some hidden rationale? Seems quite inexplicable to me.
This sadly doesn't work: long[] longs = new long[]{1L}; ArrayList<Long> longArray = new ArrayList<Long>(longs); Is there a nicer way except adding them manually?
I have some native C++ code that I'm converting to Java using SWIG so that my Java application can use it. In particular there are some functions that return std::vector. Here's a snippet of my interface file: %include "std_vector.i" namespace std { %template(Vector) vector<double>; %template(Matrix) vector<vector<double> >; } %include "std_string.i" std_string.i and s...
In Eclipse, I see that ArrayList objects have a modCount field. What is its purpose? (number of modifications?)
I've been trying to extend the ArrayList class without much success. I want to extend it, and be able to parameterize it. So normally you have something like ArrayList<SomeObject> list = new ArrayList<SomeObject>(); I want MyList<SomeObject> list = new MyList<SomeObject>(); Simply extending ArrayList doesn't work. public class MyList extends ArrayList ... The ...
There is a requirement to load a list of items(ArrayList) from two different tables. Due to complex Hibernate mapping, they can not be loaded as one ArrayList. So they are loaded separately by two different Hibernate bags in the class definition. When I use them I'd like to combine into single list. So I am thinking about writing a function as follows, private List<Item> combinedList = n...
Can anyone let me know some example situations where Template Method - pattern should be used? Give me some real-world use from your own experience. (I have so far found it useful only for mapping data in the DA layer. Sorry!!!)
I have a very simple snippet of code that populates a vector, iterates through it, and then clears it. Here is basically what I'm trying in principle: vector v = new Vector(); v.add(1); v.add(2); v.add(3); ListIterator iter = v.listIterator(); while (iter.hasNext()) { System.out.println(iter.next()); } v.clear() But I get a ConcurrentModificationException. From reading up on this, ap...
I want to compare two lists. Since we code to interface using List, which does not inherit the equals from from the Object class. How do I do this?
What is the most efficient way of sorting only a part of ArrayList? Say all elements from index 0 to 3 in an Arraylist which contains 10 elements. Is there a library function available in Java? Apart from Collections.sort(list) which sorts the entire List! Writing a highly optimised custom sort function will take some work.
I'm a student and fairly new to Java. I was looking over the different speeds achieved by the two collections in Java, Linked List, and ArrayList. I know that an ArrayList is much much faster at looking up and placing in values into its indexes. My question is: how can one make a linked list faster, if at all possible? Thanks for any help. zmahir
An abstract base class (interface class) usually has all its member functions abstract. However, I have several cases where member functions consisting of calls to the abstract methods of the interface are used. I can implement them in a derived-but-still-abstract class, or I can implemented the methods as non-abstract, non-virtual methods of the interface class. Are there any problems design...
So, im trying to implement the bottomupheap algorithm here: http://www.apl.jhu.edu/Classes/Notes/Felikson/courses/605202/lectures/L8/L8.html Algorithm bottomUpHeap(S) Input: a sequence S storing 2h-1 keys Output: a heap H storing the keys in S if S is empty then return an empty heap remove the first key, k, from S Split S into subsequences S1 and S2, each of size (n-1)/2 H1¬ bottomUpHeap(...
What does it mean for a method to be public/private/other in java? What are the advantages and disadvantages of these options? What is my impetus, as someone trying to be a good programmer, to care?
consider I have an array list like : [2,5,1,8,6] and I want to remove all elements from 1 till the end .and the arraylist will be like :[2,5] how can i do this? thanks
I have a class implementing List interface and storing data in an array of Objects. Now I need to write Iterator method for my class. How to get started ? I thought about writing a subclass implementing Iterator interface. Object of the class will have parameters of current index and last index. At each call to next/hasNext those parameters will be modified. Is this approach correct ? But then ...
What is the equivalent of C# CollectionBase in Java?
In my unit test class, I am having two list. One is the expectedValue and other is returnedType. I am doing Collections.sort(expected); Collections.sort(returned); but how do I compare two list based on the type of value of one of its element? For example I have element sortOrder in both the list and it has values from 1,2 or 3 so how do i compare or say doing something like assertEqual(ex...
Hi How can i get last three values of list.i tried this stringAry.get(stringAry.size()-1); But it displays only last item of list. How can we get last three values of list. pls guide me. Is that possible to store all this three values in String array
I posted a question earlier regarding how to extract the first eight values from an external text file using Java. The text file contains the first 1000 prime numbers and I have written a method to read the data from said text file. I would like to know how to extract eight values at random and apply the results to another method. Something along the lines of: read data from file; select ei...
  /*
   * Copyright 1997-2007 Sun Microsystems, Inc.  All Rights Reserved.
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   *
   * This code is free software; you can redistribute it and/or modify it
   * under the terms of the GNU General Public License version 2 only, as
   * published by the Free Software Foundation.  Sun designates this
   * particular file as subject to the "Classpath" exception as provided
   * by Sun in the LICENSE file that accompanied this code.
  *
  * This code is distributed in the hope that it will be useful, but WITHOUT
  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  * version 2 for more details (a copy is included in the LICENSE file that
  * accompanied this code).
  *
  * You should have received a copy of the GNU General Public License version
  * 2 along with this work; if not, write to the Free Software Foundation,
  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  *
  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  * CA 95054 USA or visit www.sun.com if you need additional information or
  * have any questions.
  */
 
 package java.util;

This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a "random access" data store (such as an array). For sequential access data (such as a linked list), AbstractSequentialList should be used in preference to this class.

To implement an unmodifiable list, the programmer needs only to extend this class and provide implementations for the get(int) and size() methods.

To implement a modifiable list, the programmer must additionally override the set(int, E) method (which otherwise throws an UnsupportedOperationException). If the list is variable-size the programmer must additionally override the add(int, E) and remove(int) methods.

The programmer should generally provide a void (no argument) and collection constructor, as per the recommendation in the Collection interface specification.

Unlike the other abstract collection implementations, the programmer does not have to provide an iterator implementation; the iterator and list iterator are implemented by this class, on top of the "random access" methods: get(int), set(int, E), add(int, E) and remove(int).

The documentation for each non-abstract method in this class describes its implementation in detail. Each of these methods may be overridden if the collection being implemented admits a more efficient implementation.

This class is a member of the Java Collections Framework.

Author(s):
Josh Bloch
Neal Gafter
Since:
1.2
 
 
 public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
    
Sole constructor. (For invocation by subclass constructors, typically implicit.)
 
     protected AbstractList() {
     }

    
Appends the specified element to the end of this list (optional operation).

Lists that support this operation may place limitations on what elements may be added to this list. In particular, some lists will refuse to add null elements, and others will impose restrictions on the type of elements that may be added. List classes should clearly specify in their documentation any restrictions on what elements may be added.

This implementation calls add(size(), e).

Note that this implementation throws an UnsupportedOperationException unless add(int, E) is overridden.

Parameters:
e element to be appended to this list
Returns:
true (as specified by Collection.add(java.lang.Object))
Throws:
java.lang.UnsupportedOperationException if the add operation is not supported by this list
java.lang.ClassCastException if the class of the specified element prevents it from being added to this list
java.lang.NullPointerException if the specified element is null and this list does not permit null elements
java.lang.IllegalArgumentException if some property of this element prevents it from being added to this list
    public boolean add(E e) {
        add(size(), e);
        return true;
    }

    
    abstract public E get(int index);

    
    public E set(int index, E element) {
        throw new UnsupportedOperationException();
    }

    
    public void add(int index, E element) {
        throw new UnsupportedOperationException();
    }

    

This implementation always throws an UnsupportedOperationException.

    public E remove(int index) {
        throw new UnsupportedOperationException();
    }
    // Search Operations

    

This implementation first gets a list iterator (with listIterator()). Then, it iterates over the list until the specified element is found or the end of the list is reached.

    public int indexOf(Object o) {
        ListIterator<E> e = listIterator();
        if (o==null) {
            while (e.hasNext())
                if (e.next()==null)
                    return e.previousIndex();
        } else {
            while (e.hasNext())
                if (o.equals(e.next()))
                    return e.previousIndex();
        }
        return -1;
    }

    

This implementation first gets a list iterator that points to the end of the list (with listIterator(size())). Then, it iterates backwards over the list until the specified element is found, or the beginning of the list is reached.

    public int lastIndexOf(Object o) {
        ListIterator<E> e = listIterator(size());
        if (o==null) {
            while (e.hasPrevious())
                if (e.previous()==null)
                    return e.nextIndex();
        } else {
            while (e.hasPrevious())
                if (o.equals(e.previous()))
                    return e.nextIndex();
        }
        return -1;
    }
    // Bulk Operations

    
Removes all of the elements from this list (optional operation). The list will be empty after this call returns.

This implementation calls removeRange(0, size()).

Note that this implementation throws an UnsupportedOperationException unless remove(int index) or removeRange(int fromIndex, int toIndex) is overridden.

Throws:
java.lang.UnsupportedOperationException if the clear operation is not supported by this list
    public void clear() {
        removeRange(0, size());
    }

    

This implementation gets an iterator over the specified collection and iterates over it, inserting the elements obtained from the iterator into this list at the appropriate position, one at a time, using add(int, E). Many implementations will override this method for efficiency.

Note that this implementation throws an UnsupportedOperationException unless add(int, E) is overridden.

    public boolean addAll(int indexCollection<? extends E> c) {
        rangeCheckForAdd(index);
        boolean modified = false;
        Iterator<? extends E> e = c.iterator();
        while (e.hasNext()) {
            add(index++, e.next());
            modified = true;
        }
        return modified;
    }
    // Iterators

    
Returns an iterator over the elements in this list in proper sequence.

This implementation returns a straightforward implementation of the iterator interface, relying on the backing list's size(), get(int), and remove(int) methods.

Note that the iterator returned by this method will throw an java.lang.UnsupportedOperationException in response to its remove method unless the list's remove(int) method is overridden.

This implementation can be made to throw runtime exceptions in the face of concurrent modification, as described in the specification for the (protected) modCount field.

Returns:
an iterator over the elements in this list in proper sequence
    public Iterator<E> iterator() {
        return new Itr();
    }

    

This implementation returns listIterator(0).

    public ListIterator<E> listIterator() {
        return listIterator(0);
    }

    

This implementation returns a straightforward implementation of the ListIterator interface that extends the implementation of the Iterator interface returned by the iterator() method. The ListIterator implementation relies on the backing list's get(int), set(int, E), add(int, E) and remove(int) methods.

Note that the list iterator returned by this implementation will throw an java.lang.UnsupportedOperationException in response to its remove, set and add methods unless the list's remove(int), set(int, E), and add(int, E) methods are overridden.

This implementation can be made to throw runtime exceptions in the face of concurrent modification, as described in the specification for the (protected) modCount field.

    public ListIterator<E> listIterator(final int index) {
        rangeCheckForAdd(index);
        return new ListItr(index);
    }
    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 = ;
        public boolean hasNext() {
            return  != size();
        }
        public E next() {
            checkForComodification();
            try {
                int i = ;
                E next = get(i);
                 = i;
                 = i + 1;
                return next;
            } catch (IndexOutOfBoundsException e) {
                checkForComodification();
                throw new NoSuchElementException();
            }
        }
        public void remove() {
            if ( < 0)
                throw new IllegalStateException();
            checkForComodification();
            try {
                AbstractList.this.remove();
                if ( < )
                    --;
                 = -1;
                 = ;
            } catch (IndexOutOfBoundsException e) {
                throw new ConcurrentModificationException();
            }
        }
        final void checkForComodification() {
            if ( != )
                throw new ConcurrentModificationException();
        }
    }
    private class ListItr extends Itr implements ListIterator<E> {
        ListItr(int index) {
             = index;
        }
        public boolean hasPrevious() {
            return  != 0;
        }
        public E previous() {
            checkForComodification();
            try {
                int i =  - 1;
                E previous = get(i);
                 =  = i;
                return previous;
            } catch (IndexOutOfBoundsException e) {
                checkForComodification();
                throw new NoSuchElementException();
            }
        }
        public int nextIndex() {
            return ;
        }
        public int previousIndex() {
            return -1;
        }
        public void set(E e) {
            if ( < 0)
                throw new IllegalStateException();
            checkForComodification();
            try {
                AbstractList.this.set(e);
                 = ;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
        public void add(E e) {
            checkForComodification();
            try {
                int i = ;
                AbstractList.this.add(ie);
                 = -1;
                 = i + 1;
                 = ;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
    }

    

This implementation returns a list that subclasses AbstractList. The subclass stores, in private fields, the offset of the subList within the backing list, the size of the subList (which can change over its lifetime), and the expected modCount value of the backing list. There are two variants of the subclass, one of which implements RandomAccess. If this list implements RandomAccess the returned list will be an instance of the subclass that implements RandomAccess.

The subclass's set(int, E), get(int), add(int, E), remove(int), addAll(int, Collection) and removeRange(int, int) methods all delegate to the corresponding methods on the backing abstract list, after bounds-checking the index and adjusting for the offset. The addAll(Collection c) method merely returns addAll(size, c).

The listIterator(int) method returns a "wrapper object" over a list iterator on the backing list, which is created with the corresponding method on the backing list. The iterator method merely returns listIterator(), and the size method merely returns the subclass's size field.

All methods first check to see if the actual modCount of the backing list is equal to its expected value, and throw a ConcurrentModificationException if it is not.

Throws:
java.lang.IndexOutOfBoundsException if an endpoint index value is out of range (fromIndex < 0 || toIndex > size)
java.lang.IllegalArgumentException if the endpoint indices are out of order (fromIndex > toIndex)
    public List<E> subList(int fromIndexint toIndex) {
        return (this instanceof RandomAccess ?
                new RandomAccessSubList<E>(thisfromIndextoIndex) :
                new SubList<E>(thisfromIndextoIndex));
    }
    // Comparison and hashing

    
Compares the specified object with this list for equality. Returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal. (Two elements e1 and e2 are equal if (e1==null ? e2==null : e1.equals(e2)).) In other words, two lists are defined to be equal if they contain the same elements in the same order.

This implementation first checks if the specified object is this list. If so, it returns true; if not, it checks if the specified object is a list. If not, it returns false; if so, it iterates over both lists, comparing corresponding pairs of elements. If any comparison returns false, this method returns false. If either iterator runs out of elements before the other it returns false (as the lists are of unequal length); otherwise it returns true when the iterations complete.

Parameters:
o the object to be compared for equality with this list
Returns:
true if the specified object is equal to this list
    public boolean equals(Object o) {
        if (o == this)
            return true;
        if (!(o instanceof List))
            return false;
        ListIterator<E> e1 = listIterator();
        ListIterator e2 = ((Listo).listIterator();
        while(e1.hasNext() && e2.hasNext()) {
            E o1 = e1.next();
            Object o2 = e2.next();
            if (!(o1==null ? o2==null : o1.equals(o2)))
                return false;
        }
        return !(e1.hasNext() || e2.hasNext());
    }

    
Returns the hash code value for this list.

This implementation uses exactly the code that is used to define the list hash function in the documentation for the List.hashCode() method.

Returns:
the hash code value for this list
    public int hashCode() {
        int hashCode = 1;
        for (E e : this)
            hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
        return hashCode;
    }

    
Removes from this list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive. Shifts any succeeding elements to the left (reduces their index). This call shortens the list by (toIndex - fromIndex) elements. (If toIndex==fromIndex, this operation has no effect.)

This method is called by the clear operation on this list and its subLists. Overriding this method to take advantage of the internals of the list implementation can substantially improve the performance of the clear operation on this list and its subLists.

This implementation gets a list iterator positioned before fromIndex, and repeatedly calls ListIterator.next followed by ListIterator.remove until the entire range has been removed. Note: if ListIterator.remove requires linear time, this implementation requires quadratic time.

Parameters:
fromIndex index of first element to be removed
toIndex index after last element to be removed
    protected void removeRange(int fromIndexint toIndex) {
        ListIterator<E> it = listIterator(fromIndex);
        for (int i=0, n=toIndex-fromIndexi<ni++) {
            it.next();
            it.remove();
        }
    }

    
The number of times this list has been structurally modified. Structural modifications are those that change the size of the list, or otherwise perturb it in such a fashion that iterations in progress may yield incorrect results.

This field is used by the iterator and list iterator implementation returned by the iterator and listIterator methods. If the value of this field changes unexpectedly, the iterator (or list iterator) will throw a ConcurrentModificationException in response to the next, remove, previous, set or add operations. This provides fail-fast behavior, rather than non-deterministic behavior in the face of concurrent modification during iteration.

Use of this field by subclasses is optional. If a subclass wishes to provide fail-fast iterators (and list iterators), then it merely has to increment this field in its add(int, E) and remove(int) methods (and any other methods that it overrides that result in structural modifications to the list). A single call to add(int, E) or remove(int) must add no more than one to this field, or the iterators (and list iterators) will throw bogus ConcurrentModificationExceptions. If an implementation does not wish to provide fail-fast iterators, this field may be ignored.

    protected transient int modCount = 0;
    private void rangeCheckForAdd(int index) {
        if (index < 0 || index > size())
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size();
    }
class SubList<E> extends AbstractList<E> {
    private final AbstractList<E> l;
    private final int offset;
    private int size;
    SubList(AbstractList<E> listint fromIndexint toIndex) {
        if (fromIndex < 0)
            throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
        if (toIndex > list.size())
            throw new IndexOutOfBoundsException("toIndex = " + toIndex);
        if (fromIndex > toIndex)
            throw new IllegalArgumentException("fromIndex(" + fromIndex +
                                               ") > toIndex(" + toIndex + ")");
         = list;
         = fromIndex;
         = toIndex - fromIndex;
        this. = .;
    }
    public E set(int index, E element) {
        rangeCheck(index);
        checkForComodification();
        return .set(index+element);
    }
    public E get(int index) {
        rangeCheck(index);
        checkForComodification();
        return .get(index+);
    }
    public int size() {
        checkForComodification();
        return ;
    }
    public void add(int index, E element) {
        rangeCheckForAdd(index);
        checkForComodification();
        .add(index+element);
        this. = .;
        ++;
    }
    public E remove(int index) {
        rangeCheck(index);
        checkForComodification();
        E result = .remove(index+);
        this. = .;
        --;
        return result;
    }
    protected void removeRange(int fromIndexint toIndex) {
        checkForComodification();
        .removeRange(fromIndex+toIndex+);
        this. = .;
         -= (toIndex-fromIndex);
    }
    public boolean addAll(Collection<? extends E> c) {
        return addAll(c);
    }
    public boolean addAll(int indexCollection<? extends E> c) {
        rangeCheckForAdd(index);
        int cSize = c.size();
        if (cSize==0)
            return false;
        checkForComodification();
        .addAll(+indexc);
        this. = .;
         += cSize;
        return true;
    }
    public Iterator<E> iterator() {
        return listIterator();
    }
    public ListIterator<E> listIterator(final int index) {
        checkForComodification();
        rangeCheckForAdd(index);
        return new ListIterator<E>() {
            private final ListIterator<E> i = .listIterator(index+);
            public boolean hasNext() {
                return nextIndex() < ;
            }
            public E next() {
                if (hasNext())
                    return .next();
                else
                    throw new NoSuchElementException();
            }
            public boolean hasPrevious() {
                return previousIndex() >= 0;
            }
            public E previous() {
                if (hasPrevious())
                    return .previous();
                else
                    throw new NoSuchElementException();
            }
            public int nextIndex() {
                return .nextIndex() - ;
            }
            public int previousIndex() {
                return .previousIndex() - ;
            }
            public void remove() {
                .remove();
                SubList.this. = .;
                --;
            }
            public void set(E e) {
                .set(e);
            }
            public void add(E e) {
                .add(e);
                SubList.this. = .;
                ++;
            }
        };
    }
    public List<E> subList(int fromIndexint toIndex) {
        return new SubList<E>(thisfromIndextoIndex);
    }
    private void rangeCheck(int index) {
        if (index < 0 || index >= )
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
    private void rangeCheckForAdd(int index) {
        if (index < 0 || index > )
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+;
    }
    private void checkForComodification() {
        if (this. != .)
            throw new ConcurrentModificationException();
    }
class RandomAccessSubList<E> extends SubList<E> implements RandomAccess {
    RandomAccessSubList(AbstractList<E> listint fromIndexint toIndex) {
        super(listfromIndextoIndex);
    }
    public List<E> subList(int fromIndexint toIndex) {
        return new RandomAccessSubList<E>(thisfromIndextoIndex);
    }
New to GrepCode? Check out our FAQ X