Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
I have a String of the format "[(1, 2), (2, 3), (3, 4)]", with an arbitrary number of elements. I'm trying to split it on the commas separating the coordinates, that is, to retrieve (1, 2), (2, 3), and (3, 4). Can I do it in Java regex? I'm a complete noob but hoping Java regex is powerful enough for it. If it isn't, could you suggest an alternative?
I have defined a Java function: static <T> List<T> createEmptyList() { return new ArrayList<T>(); } One way to call it is like so: List<Integer> myList = createEmptyList(); // Compiles Why can't I call it by explicitly passing the generic type argument? : Object myObject = createEmtpyList<Integer>(); // Doesn't compile. Why? I get the error "Illegal st...
In one of my Java 6 projects I have an array of LinkedHashMap instances as input to a method which has to iterate through all keys (i.e. through the union of the key sets of all maps) and work with the associated values. Not all keys exist in all maps and the method should not go through each key more than once or alter the input maps. My current implementation looks like this: Set<Object&...
When you call remove(object o) on an arraylist in java, how does it compare the objects to find the correct one to remove? does it use the pointer? or does it compare the objects using the interface Comparable?
Right now, I have: public <T> T[] toArray(T[] old) { T[] arr = Arrays.copyOf(old, old.length + size()); int i = old.length; for(E obj : this) { arr[i] = old.getClass().getComponentType().cast(obj); ++i; } return arr; } (Note that this does not follow the contract as it was pointed out by axtavt.) where I get this ...
I need to get a String[] out of a Set<String>, but I don't know how to do it. The following fails: Map<String, ?> myMap = gpxlist.getAll(); Set<String> myset = myMap.keySet(); String[] GPXFILES1 = (String[]) myset.toArray(); // Here it fails. How can I fix it so that it works?
I have 2 ArrayLists that have a Array of Strings as a "component". I want to find the "components" whose first element is the same in both ArrayLists. To be more clear: ArrayList One first component => {"0", "zero"} second component => {"1", "one"} ArrayList Two first component => {"1", "uno"} second component => {"2", "two"} I would like to loop through ArrayList Two and find {"...
I have a bunch of indexes and I want to remove elements at these indexes from an ArrayList. I can't do a simple sequence of remove()s because the elements are shifted after each removal. How do I solve this?
I have a question about where to document logic in javadocs. For example, I have the following method signature in an interface: public int getTotalAssociationsAsParent(Long id, Long type); The method returns associations where the given ID is the parent and the association is of type 'type'. ID is required, but if type passed in is NULL, then I will return ALL associations where the ID is...
I am trying to create a class say MyStack that would implement a java.util.collections class. MyStack will override some methods of the collections class like add(similar to push), remove(similar to pop) etc.. I intend to model the class on the same lines as a Set or other interfaces of the collection class except that MyStack would not be an interface or abstract class and that we can create...
Set<Type> union = new HashSet<Type>(s1); And Set<Type> union = new HashSet<Type>(); Set<Type> s1 = new HashSet<Type>(); union.addAll(s1);
I have a bunch of objects of a class Puzzle. I have overridden equals() and hashCode(). When it comes time to present the solutions to the user, I'd like to filter out all the Puzzles that are "similar" (by the standard I have defined), so the user only sees one of each. Similarity is transitive. Example: Result of computations: A (similar to A) B (similar to C) C D In this case, onl...
Ok, so this question will probably get closed, but hell, its 4:30 in the morning and I can't sleep because I'm still frustrated with my Java midterm last night. The test was an on-line thing and you get to see how you did immediately. The test was poorly written with tons of typos and grammatical errors. I don't normally care about that, except that when you add in vaguely phrased questions ...
This is a related (and or follow up) issue to : Event Function called before Setter So Given i have : <Td> <h:selectOneMenu id="combocarList" value="#{customerBean.selectedcar}" styleClass="comboStyle" valueChangeListener="#{customerBean.loadothercombos}" onchange="document.forms[0].submit()" > <f:selectItem itemLabel="-----------Select--------------" itemValue="None"...
in order to separate java code and html code and be more faithful to MVC framework i am coding like that; in the servlet i put the following: net.sf.hibernate.Session s = null; net.sf.hibernate.Transaction tx; try { s= HibernateUtil.currentSession(); tx=s.beginTransaction(); Query query = s.createQuery("select opcemployees.Nom,opcemployees.Prenom,dailytimesh...
The toString method is not overridden in Set or its hierarchy, so how are the elements printed? import java.lang.Math; import java.util.HashSet; class Hello{ public String name= ""; Hello(String name){ this.name = name; } public static void main(String args[]){ Hello h1 = new Hello("first"); Hello h2 = new Hello("second"); Hello h3 = new Hello("third"); Hello h4 = new Hello(...
I am trying to convert a String into an ArrayList. For example, my Struts2 webapp returns this String named row in a format similar to this: [A, BB, CCC, DDDD, 1, 0, 1] (something along those lines) I need to convert them into an ArrayList so I can prepopulate some forms in another JSP page. I hardcoded a method to convert such Strings into list form: StringBuffer rowBuffer = new Str...
i have an arraylist called Module, i want to create a method that will delete a module from the ArrayList based on the index passed as the parameter. this is what i have so far but it isn't working. any suggestions please (beginner)? Simon /** * This method deletes a module object from the ArrayList * @param theModule The module object that will be deleted from the ArraList */ public voi...
list all modules in the ArraryList? - I thought it'd be something like below but this won't compile (error - cannot find symbol - method list). /** * This method lists all modules in the ArrayList */ public String listAllModules() { return modules.list(); } Thanks. (new to Java in case that isn't obvious..)
How can I implement a collection using a linked list by extending the Abstract collection? I'd have to use the void remove method if Iterator, and implement this and the add and size methods.
I have a List and I want to pass it to the subsequent request as GET query string parameter: <a href="servlet?list=<%=request.getAttribute("list")%>">link</a> Inside the servlet I am trying to retrieve it as follows: String[] list = req.getParameterValues("list"); It does not work. How can I get it to work?
  /*
   * Copyright 1997-2006 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 Collection interface, to minimize the effort required to implement this interface.

To implement an unmodifiable collection, the programmer needs only to extend this class and provide implementations for the iterator and size methods. (The iterator returned by the iterator method must implement hasNext and next.)

To implement a modifiable collection, the programmer must additionally override this class's add method (which otherwise throws an UnsupportedOperationException), and the iterator returned by the iterator method must additionally implement its remove method.

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

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
See also:
Collection
 
 
 public abstract class AbstractCollection<E> implements Collection<E> {
    
Sole constructor. (For invocation by subclass constructors, typically implicit.)
 
     protected AbstractCollection() {
     }
 
     // Query Operations
 
    
Returns an iterator over the elements contained in this collection.

Returns:
an iterator over the elements contained in this collection
 
     public abstract Iterator<E> iterator();
 
     public abstract int size();

    

This implementation returns size() == 0.

 
     public boolean isEmpty() {
         return size() == 0;
     }

    

This implementation iterates over the elements in the collection, checking each element in turn for equality with the specified element.

 
     public boolean contains(Object o) {
         Iterator<E> e = iterator();
        if (o==null) {
            while (e.hasNext())
                if (e.next()==null)
                    return true;
        } else {
            while (e.hasNext())
                if (o.equals(e.next()))
                    return true;
        }
        return false;
    }

    

This implementation returns an array containing all the elements returned by this collection's iterator, in the same order, stored in consecutive elements of the array, starting with index 0. The length of the returned array is equal to the number of elements returned by the iterator, even if the size of this collection changes during iteration, as might happen if the collection permits concurrent modification during iteration. The size method is called only as an optimization hint; the correct result is returned even if the iterator returns a different number of elements.

This method is equivalent to:

 List<E> list = new ArrayList<E>(size());
 for (E e : this)
     list.add(e);
 return list.toArray();
 
    public Object[] toArray() {
        // Estimate size of array; be prepared to see more or fewer elements
        Object[] r = new Object[size()];
        Iterator<E> it = iterator();
        for (int i = 0; i < r.lengthi++) {
            if (! it.hasNext()) // fewer elements than expected
                return Arrays.copyOf(ri);
            r[i] = it.next();
        }
        return it.hasNext() ? finishToArray(rit) : r;
    }

    

This implementation returns an array containing all the elements returned by this collection's iterator in the same order, stored in consecutive elements of the array, starting with index 0. If the number of elements returned by the iterator is too large to fit into the specified array, then the elements are returned in a newly allocated array with length equal to the number of elements returned by the iterator, even if the size of this collection changes during iteration, as might happen if the collection permits concurrent modification during iteration. The size method is called only as an optimization hint; the correct result is returned even if the iterator returns a different number of elements.

This method is equivalent to:

 List<E> list = new ArrayList<E>(size());
 for (E e : this)
     list.add(e);
 return list.toArray(a);
 

    public <T> T[] toArray(T[] a) {
        // Estimate size of array; be prepared to see more or fewer elements
        int size = size();
        T[] r = a.length >= size ? a :
                  (T[])java.lang.reflect.Array
                  .newInstance(a.getClass().getComponentType(), size);
        Iterator<E> it = iterator();
        for (int i = 0; i < r.lengthi++) {
            if (! it.hasNext()) { // fewer elements than expected
                if (a != r)
                    return Arrays.copyOf(ri);
                r[i] = null// null-terminate
                return r;
            }
            r[i] = (T)it.next();
        }
        return it.hasNext() ? finishToArray(rit) : r;
    }

    
Reallocates the array being used within toArray when the iterator returned more elements than expected, and finishes filling it from the iterator.

Parameters:
r the array, replete with previously stored elements
it the in-progress iterator over this collection
Returns:
array containing the elements in the given array, plus any further elements returned by the iterator, trimmed to size
    private static <T> T[] finishToArray(T[] rIterator<?> it) {
        int i = r.length;
        while (it.hasNext()) {
            int cap = r.length;
            if (i == cap) {
                int newCap = ((cap / 2) + 1) * 3;
                if (newCap <= cap) { // integer overflow
                    if (cap == .)
                        throw new OutOfMemoryError
                            ("Required array size too large");
                    newCap = .;
                }
                r = Arrays.copyOf(rnewCap);
            }
            r[i++] = (T)it.next();
        }
        // trim if overallocated
        return (i == r.length) ? r : Arrays.copyOf(ri);
    }
    // Modification Operations

    
    public boolean add(E e) {
        throw new UnsupportedOperationException();
    }

    

This implementation iterates over the collection looking for the specified element. If it finds the element, it removes the element from the collection using the iterator's remove method.

Note that this implementation throws an UnsupportedOperationException if the iterator returned by this collection's iterator method does not implement the remove method and this collection contains the specified object.

    public boolean remove(Object o) {
        Iterator<E> e = iterator();
        if (o==null) {
            while (e.hasNext()) {
                if (e.next()==null) {
                    e.remove();
                    return true;
                }
            }
        } else {
            while (e.hasNext()) {
                if (o.equals(e.next())) {
                    e.remove();
                    return true;
                }
            }
        }
        return false;
    }
    // Bulk Operations

    

This implementation iterates over the specified collection, checking each element returned by the iterator in turn to see if it's contained in this collection. If all elements are so contained true is returned, otherwise false.

    public boolean containsAll(Collection<?> c) {
        Iterator<?> e = c.iterator();
        while (e.hasNext())
            if (!contains(e.next()))
                return false;
        return true;
    }

    

This implementation iterates over the specified collection, and adds each object returned by the iterator to this collection, in turn.

Note that this implementation will throw an UnsupportedOperationException unless add is overridden (assuming the specified collection is non-empty).

    public boolean addAll(Collection<? extends E> c) {
        boolean modified = false;
        Iterator<? extends E> e = c.iterator();
        while (e.hasNext()) {
            if (add(e.next()))
                modified = true;
        }
        return modified;
    }

    

This implementation iterates over this collection, checking each element returned by the iterator in turn to see if it's contained in the specified collection. If it's so contained, it's removed from this collection with the iterator's remove method.

Note that this implementation will throw an UnsupportedOperationException if the iterator returned by the iterator method does not implement the remove method and this collection contains one or more elements in common with the specified collection.

    public boolean removeAll(Collection<?> c) {
        boolean modified = false;
        Iterator<?> e = iterator();
        while (e.hasNext()) {
            if (c.contains(e.next())) {
                e.remove();
                modified = true;
            }
        }
        return modified;
    }

    

This implementation iterates over this collection, checking each element returned by the iterator in turn to see if it's contained in the specified collection. If it's not so contained, it's removed from this collection with the iterator's remove method.

Note that this implementation will throw an UnsupportedOperationException if the iterator returned by the iterator method does not implement the remove method and this collection contains one or more elements not present in the specified collection.

    public boolean retainAll(Collection<?> c) {
        boolean modified = false;
        Iterator<E> e = iterator();
        while (e.hasNext()) {
            if (!c.contains(e.next())) {
                e.remove();
                modified = true;
            }
        }
        return modified;
    }

    

This implementation iterates over this collection, removing each element using the Iterator.remove operation. Most implementations will probably choose to override this method for efficiency.

Note that this implementation will throw an UnsupportedOperationException if the iterator returned by this collection's iterator method does not implement the remove method and this collection is non-empty.

    public void clear() {
        Iterator<E> e = iterator();
        while (e.hasNext()) {
            e.next();
            e.remove();
        }
    }
    //  String conversion

    
Returns a string representation of this collection. The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (comma and space). Elements are converted to strings as by java.lang.String.valueOf(java.lang.Object).

Returns:
a string representation of this collection
    public String toString() {
        Iterator<E> i = iterator();
        if (! i.hasNext())
            return "[]";
        StringBuilder sb = new StringBuilder();
        sb.append('[');
        for (;;) {
            E e = i.next();
            sb.append(e == this ? "(this Collection)" : e);
            if (! i.hasNext())
                return sb.append(']').toString();
            sb.append(", ");
        }
    }
New to GrepCode? Check out our FAQ X