Generic collections. It's a bug?

I'm new in Java 5 and I have seen that we can insert elements of any type in a typed collection!! , so, its not sure to use them? Have I to check all the elements in the collections received from parameters ?
public static void main(String argv[]){   
     Ejemplo e = new Ejemplo();      
     List lista1 = new ArrayList();
     lista1.add("this is not Ejemplo");
     List<Ejemplo> lista = lista1;
     lista.add(e);
     lista.add(e);
//ClassCastException
     for(Ejemplo i:lista){
          System.out.println(i);
}

That's why you'll get an "unchecked" warning from the compiler when you do the list assignment. It's warning you that there's no certainty that the list has the right type of contents.
The trouble with generics is that you can get a lot of these warnings, some that you really can't avoid. You need to look at them and be confident that the generic type is valid.
Of course, had you not been using generics, you have had to write the loop casting the element explicity to (Ejemplo), which would still have given you the ClassCastException.

Similar Messages

  • I have the CC Master Collection, I am experiencing bugs in version 18.1.0.

    I have the CC Master Collection, I am experiencing bugs in Illustrator version 18.1.0.
    It appears I do not have Illustrator CC2014.1 (can't tell since you don't list the version number anywhere!), but I can't seem to download it. I go to the download page from the link in this forum and nothing downloads, It just says it is downloading. I get the CC widget from my mac menu poping up, and it says all the Apps are up to date. I had a colleague who had a problem of CC saying CC Acrobat Pro was up to date when it clearly was not the current  X.x.x version, I am thinking this may be a problem here as well.  I really need to talk to someone I think, but there seems to be no way to get to a chat or live person. This seems like pretty bad service so far...
    The bugs I am seeing is I can  not set a line wight to less than 1 pt. and the items o move around seem to be snapping to a pixel sized (1/72 in) grid instead of where I actually move them. I have confirmed the snap to grid is off in the menu. I can also not set the key increment move meant to more than 2 decimal places. In CS6 I could go 3 decimal places.
    What the heck is going on, and doesn't recent purchase of the Adobe CC Master collection rate something more direct than a forum?
    Britt
    Just found the answer to some of my issues. The Alight to pixel grid command was on (what a painful feature to be on by default!) "When I select .25 line width, the line width defaults to 1 pt., how do I fix that?"
    Now if I could just confirm if I am current with the Program version...

    NASADeploymentsETLA wrote:
    What the heck is going on, and doesn't recent purchase of the Adobe CC Master collection rate something more direct than a forum?
    hah!

  • variable-class using Generic Collection

    Within my TLDs I would like to use the <variable-class> attribute as much as possible for the sake of JSP authors.
    I cannot figure out how to specify that a varAttribute will be a generic collection. IE, if I want to return a set of strings, I would like to do
    <variable-class>
    java.util.set<java.lang.String>
    </variable-class>
    Of course I must escape the <,> and I tried using < and > but it was not effective.
    Is this even possible? I would appreciate any comments suggestions.

    Currently we are using a single domain account on every machine in this kiosk area. They are using just Internet Explorer and Adobe Reader. We are using Group Policy to lock down the machines. Each station is a full computer (older Dell OptiPlex) running
    Windows 7. We are looking at the possibility of removing the OptiPlex computers and replacing them with Wyse terminals. The backend would be a cluster of 3 servers running Hyper-V 2012 R2. On those would be running Windows Server 2012 R2 RDS.  We have
    tested this setup, but when creating the VDI collection there doesn't seem to be a way to use generic domain accounts. 
    Every person that uses these does not have an AD account and it looks like that would be a problem when trying to implement this.  I was just checking here to see if anyone had any ideas or had gone through a similar setup.

  • OAM Generic Collection Services

    Hi,
    After cloning from multi node to single node, OAM Generic Collection Service is not started by default ?
    However, i manually started it.
    Is this the normal
    Thanks
    sunil

    Sunil,
    What is the error?
    Please clean FND_NODES table as follows, and run AutoConfig on the database/application tiers then:
    SQL> EXEC FND_CONC_CLONE.SETUP_CLEAN;
    SQL> COMMIT;If the above does not help, please have a look at [Note: 393706.1 - OAM Generic Collection Service shows State: The target node/queue unavailable|https://metalink2.oracle.com/metalink/plsql/ml2_documents.showDocument?p_database_id=NOT&p_id=393706.1]

  • BUG - OJC 10.1.3.2 doesn't allow upcast when adding to generic Collection

    JDeveloper: 10.1.3.2.0.4066
    Compile Errors:
    method asList(Crusty, Slush, Powder) not found in class java.util.Arrays
    method addAll(java.util.List<Snow>, Light, Heavy) not found in class java.util.Collections
    When adding a group of elements to a Collection which uses generics, the ojc compiler does not allow upcasting, but the same upcasting is permitted by the javac compiler.
    The following code is taken from Bruce Eckel's Thinking In Java, 4th edition, page 396. It reproduces the compile problems:
    import java.util.*;
    class Snow {}
    class Powder extends Snow {}
    class Light extends Powder {}
    class Heavy extends Powder {}
    class Crusty extends Snow {}
    class Slush extends Snow {}
    public class AsListInference {
      public static void main(String[] args) {
        //Following line compiles under javac but not under ojc:
        List<Snow> snow1 = Arrays.asList(new Crusty(), new Slush(), new Powder());
        System.out.println("snow1:");
        for (Snow s : snow1) {
          System.out.println(s);
        //Following line doesn't compile under javac or ojc:
        //List<Snow> snow2 = Arrays.asList(new Light(), new Heavy());
        List<Snow> snow3 = new ArrayList<Snow>();
        //Following line compiles under javac but not under ojc:
        Collections.addAll(snow3, new Light(), new Heavy());
        System.out.println("snow3:");
        for (Snow s : snow3) {
          System.out.println(s);
        //Following line compiles under both javac and ojc:
        List<Snow> snow4 = Arrays.<Snow> asList(new Light(), new Heavy());
        System.out.println("snow4:");
        for (Snow s : snow4) {
          System.out.println(s);
    }

    Loren,
    thanks will file this too
    Frank

  • Generic Collections and inheritance

    Hi all
    I have the following code:
    public class GenericTest {
         public static <T,C extends Collection<T>> C process(C collection){
              // do some stuff (using T)
              return collection; // just to make a complete methode
         public void main(String[] args){
              List<String> l1 = new ArrayList<String>();
              List<String> l2;
              l2 = process(l1); // does not compile
    }Compilation fails with message :
    Bound mismatch: The generic method process(C) of type GenericTest is not applicable for the arguments (List<String>) since the type List<String> is not a valid substitute for the bounded parameter <C extends Collection<T>>     
    My questions:
    why doesn't it work?
    How do I fix it?
    regards
    Spieler

    What Compiler are you using?
    Your code compiles just fine on the JDK 1.5 compiler (once I added an inport for java.util.*)
    If the error message is from your IDE, you should check your IDE's web site for an existing bug, and for assistance.
    This is not the correct forum since your code compiles on the SUN JDK.
    Bruce

  • How to get an exception when casting a generic collection?

    Hi,
    I have a bit of code that looks more or less like this:import java.util.ArrayList;
    import java.util.Collection;
    public class CollectionTest {
         public static void main (String[] args) {
              try {
                   get (Float.class);
              } catch (ClassCastException e) {
                   System.err.println ("Oops");
                   e.printStackTrace (System.err);
              try {
                   Collection<Short> shorts = get (Short.class);
                   for (Short s : shorts) {
                        System.out.println (s);
              } catch (ClassCastException e) {
                   System.err.println ("Oops");
                   e.printStackTrace (System.err);
              try {
                   Collection<Number> numbers = get (Number.class);
                   for (Number number : numbers) {
                        System.out.println (number);
              } catch (ClassCastException e) {
                   System.out.println ("Oops again");
                   e.printStackTrace (System.err);
         public static <T> Collection<T> get (Class<T> clazz) {
              Collection<T> ret = new ArrayList<T> ();
              if (clazz == String.class) {
                   ret.add (clazz.cast ("Test"));
              } else if (clazz == Integer.class) {
                   ret.add (clazz.cast (Integer.valueOf (1)));
              } else if (clazz == Double.class) {
                   ret.add (clazz.cast (Double.valueOf (1.0)));
              } else if (clazz == Float.class) {
                   ret.add (clazz.cast ("Bug")); // Bug here, blatent
              } else if (clazz == Short.class) {
                   ret.add ((T) "Bug"); // Bug here, latent
              } else if (clazz == Number.class) {
                   ret.addAll (get (Integer.class));
                   ret.addAll (get (Double.class));
                   ret.addAll (get (String.class)); // Another bug here, latent
              return ret;
    }Obviously this doesn't compile as-is, I have to add 3 casts towards the end. Then when I add the casts and run the program I discover I have several bugs, some of which are fail-early and some of which lie hidden until the further away from the bug Since I have the type-token, I use it to check the simple cast, but is there any way I can get a failure more or less at the point where the dodgy Collection cast is made?

    OK, sorry not to be clear. My example code is meant to crash on the erroneous casts - clearly a String cannot be cast to a Float, nor a Short. My point is that in one case the code crashes at the point where the cast is made and in another case the code crashes later on. What I want to achieve is this early failure in case of buggy code. Here is a shorter example:import java.util.ArrayList;
    import java.util.Collection;
    public class CollectionTest {     
         public static <T> Collection<T> get (Class<T> clazz) {
              Collection<T> ret = new ArrayList<T> ();
              if (clazz == String.class) {
                   ret.add (clazz.cast ("Test"));
              } else if (clazz == Integer.class) {
                   ret.add (clazz.cast (Integer.valueOf (1)));
              } else if (clazz == Double.class) {
                   ret.add (clazz.cast (Double.valueOf (1.0)));
              } else if (clazz == Number.class) {
                   ret.addAll ((Collection<? extends T>) get (Integer.class));
                   ret.addAll ((Collection<? extends T>) get (Double.class));
                    // This is a bug, but how can I get an exception at this point?
                   ret.addAll ((Collection<? extends T>) get (String.class));
              return ret;
    }If I mistakenly write this code it will compile (with the addition of the appropriate casts). However, my code is buggy and will fail when the user of the collection receives a String when he is expecting a Number. My question is, how can I get my code to fail where I make the erroneous cast? If you look at the code I originally posted I have two casts of the String "Bug", one of which is done by (T) and the other is clazz.cast. The first example fails late and the second fails early - it is this early failure that I would like to achieve, in the case of buggy code, in my example above.
    Am I making sense yet?

  • Reflection and Generic Collections

    Hi -
    I'm having trouble with reflection on Sets
    I have a set of type T extends U and want to return the class of T:
    public static <T extends U> Class<T> getSetType(Set<T> set) {
    // what to do?
    }Any help?
    Message was edited by:
    [email protected]

    parameterized types are not present at runtime, as danny basically indicated. what you want to do here is neither a generics nor a reflection issue: unless the Set is empty, you can just examine the first object it contains for it's class:
    public static <T extends U> Class<T> getSetType(Set<T> set) {
         if ( null == set ) {
            return null;
         if ( 0 == set.size() ) {
            return null;
         return set.iterator().next().getClass();
    }

  • BUG: 10.1.3..36.73 Internal Compile Error with enhanced for loop/generics

    I get the following compiler error when using the Java 5 SE enhanced for loop with a generic collection.
    Code:
    public static void main(String[] args)
    List<Integer> l = new ArrayList<Integer>();
    l.add(new Integer(1));
    printCollection(l);
    private static void printCollection(Collection<?> c)
    for (Object e : c)
    System.out.println(e);
    Error on attempting to build:
    "Error: Internal compilation error, terminated with a fatal exception"
    And the following from ojcInternalError.log:
    java.lang.NullPointerException
         at oracle.ojc.compiler.EnhancedForStatement.resolveAndCheck(Statement.java:2204)
         at oracle.ojc.compiler.StatementList.resolveAndCheck(Statement.java:4476)
         at oracle.ojc.compiler.MethodSymbol.resolveMethod(Symbol.java:10822)
         at oracle.ojc.compiler.RawClassSymbol.resolveMethodBodies(Symbol.java:6648)
         at oracle.ojc.compiler.Parser.resolveMethodBodies(Parser.java:8316)
         at oracle.ojc.compiler.Parser.parse(Parser.java:7823)
         at oracle.ojc.compiler.Compiler.main_internal(Compiler.java:978)
         at oracle.ojc.compiler.Compiler.main(Compiler.java:745)
         at oracle.jdeveloper.compiler.Ojc.translate(Ojc.java:1486)
         at oracle.jdeveloper.compiler.UnifiedBuildSystem$CompileThread.buildGraph(UnifiedBuildSystem.java:300)
         at oracle.jdeveloper.compiler.UnifiedBuildSystem$CompileThread.buildProjectFiles(UnifiedBuildSystem.java:515)
         at oracle.jdeveloper.compiler.UnifiedBuildSystem$CompileThread.buildAll(UnifiedBuildSystem.java:715)
         at oracle.jdeveloper.compiler.UnifiedBuildSystem$CompileThread.run(UnifiedBuildSystem.java:893)

    Install the Service Update 1 patch for JDeveloper (using the help->check for updates), and let us know if this didn't solve the problem.

  • Refresh Collection Snapshots Error ORA-12008 ORA-01555

    Need some insight!
    Ct is implementing R12.1.1 ASCP using existing 11.5.10 EBS as source.
    In source EBS, when running Refresh Collection Snapshots (RCS) in COMPLETE mode, we encounter this error:
    ORA-12008: error in materialized view refresh path
    ORA-01555: snapshot too old: rollback segment number 13 with name "_SYSSMU13$" too small
    ORA-12008: error in materialized view refresh path
    ORA-01555: snapshot too old: rollback segment number 13 with name "_SYSSMU13$" too small
    All the snapshot entities got refreshed successfully (in 5 minutes) but the Refresh Collection Snapshot request itself ends with ERROR (after 4 hrs).
    Appreciate your input on this one.
    Thanks,
    Jake

    Welcome to the forums !
    ORA-01555 is a common error condition. There are typically two solutions (or a combination of both) -
    1. Increase rollback / undo tablespace size
    2. Run your process when the database is not active (i.e. few or no updates/deletes/inserts etc).
    More information may be available in these MOS Docs
    211121.1 - How To Run MSRFWOR - Refresh Collections Snapshots Concurrent Request From The Application
    207644.1 - Data Collections is Failing - All Errors - First Diagnostic Steps
    306418.1 - 11.5.10 MSRFWOR: Refresh Collection Snapshot Performance Is Poor and Fails with Errors
    369173.1 - MSRFWOR Refresh Collection Snapshots Performance Database Bug 4196039
    308487.1 - Refresh Collection Snapshot Request Fails Yet The Request Shows Complete Normal
    HTH
    Srini

  • Generic interface in abstract super class

    hello java folks!
    i have a weird problem with a generics implementation of an interface which is implemented in an abstract class.
    if i extend from this abstract class and try to override the method i get this compiler error:
    cannot directly invoke abstract method...
    but in my abstract super class this method is not implemented as abstract!
    do i have an error in my understanding how to work with generics or is this a bug in javac?
    (note: the message is trown by the eclipse ide, but i think it has someting to do with javac...)
    thanks for every hint!
    greetings daniel
    examples:
    public interface MyInterface <T extends Object> {
       public String testMe(T t);
    public abstract class AbstractSuperClass<T extends AbstractSuperClass> implements MyInterface<T> {
       public String testMe(T o) {
          // do something with o...
          // now we have a String str
          return str;
    public final class SubClass extends AbstractSuperClass<SubClass> {
       @Override
       public String testMe(SubClass o)
          return super.testMe(o);
    }

    Hi Wachtda,
    Firstly, T extends Object is redundant as all classes implicitly extend the Object class.
    Therefore :
    public interface MyInterface <T> {
       public String testMe(T t);
    }Secondly, abstract classes may have both abstract and non-abstract instance methods. Also, two methods, one abstract and one non-abstract, must have a different signature.
    The following example will give a compile error because the methods share the same signature :
    abstract class Test {
         public void sayHello() {
              System.out.println("Hello");
         abstract public void sayHello();
    }Therefore, to make an interface method as abstract would simply block the possibility of implementing it.
    BTW, you can do this :
    abstract class Test {
         public void sayHello() {
              System.out.println("Hello");
         abstract public void sayHello(String name);
    }Finally, there's no bug in javac.

  • C++ API: is there a bug with Map::InvokeAll?

    Hello,
    I'm trying to use entry processors for doing like "put if absent", "delete where", ...
    I works fine except for the return values. Whatever I do, the map returned by InvokeAll is always empty!
    This a simple example:
    #include <coherence/net/cachefactory.hpp>
    #include <coherence/util/extractor/KeyExtractor.hpp>
    #include <coherence/util/filter/AlwaysFilter.hpp>
    #include <coherence/util/filter/LikeFilter.hpp>
    #include <coherence/util/filter/NotFilter.hpp>
    #include <coherence/util/filter/PresentFilter.hpp>
    #include <coherence/util/HashSet.hpp>
    #include <coherence/util/processor/ConditionalPutAll.hpp>
    #include <coherence/util/processor/ConditionalRemove.hpp>
    namespace ch = coherence::net;
    namespace cu = coherence::util;
    namespace cl = coherence::lang;
    namespace {
    void dumpMap(cu::Set::View vSetResult, const std::string &message)
    std::cerr<<message<<": ";
    for (cu::Iterator::Handle hIter = vSetResult->iterator(); hIter->hasNext(); )
    cu::Map::Entry::View vEntry = cl::cast<cu::Map::Entry::View>(hIter->next());
    cl::String::View key = cl::cast<cl::String::View>(vEntry->getKey());
    cl::String::View val = cl::cast<cl::String::View>(vEntry->getValue());
    std::cerr<<"("<<vEntry->getKey()<<","<<vEntry->getValue()<<"), ";
    std::cerr<<std::endl;
    void dumpCache(ch::NamedCache::Handle hCache, const std::string &message)
    dumpMap(hCache->entrySet(), message);
    void initCache(ch::NamedCache::Handle hCache)
    hCache->clear();
    hCache->put(cl::String::create("01"), cl::String::create("v:01"));
    hCache->put(cl::String::create("05"), cl::String::create("v:05"));
    hCache->put(cl::String::create("11"), cl::String::create("v:11"));
    hCache->put(cl::String::create("15"), cl::String::create("v:15"));
    hCache->put(cl::String::create("21"), cl::String::create("v:21"));
    hCache->put(cl::String::create("25"), cl::String::create("v:25"));
    void testInvokeAll()
    ch::NamedCache::Handle hCache(ch::CacheFactory::getCache("first_cache"));
    std::cerr<<"== init"<<std::endl;
    initCache(hCache);
    dumpCache(hCache, "init");
    std::cerr<<"== emulation putIfAbsent"<<std::endl;
    cu::Map::Handle entries = cu::HashMap::create();
    entries->put(cl::String::create("01"), cl::String::create("v:01MOD"));
    entries->put(cl::String::create("==="), cl::String::create("===MOD"));
    entries->put(cl::String::create("11"), cl::String::create("v:11MOD"));
    entries->put(cl::String::create("+++"), cl::String::create("+++MOD"));
    cu::InvocableMap::EntryProcessor::Handle processor = cu::processor::ConditionalPutAll::create(
    cu::filter::NotFilter::create(cu::filter::PresentFilter::getInstance()), entries);
    cu::Map::View res = hCache->invokeAll(cl::cast<cu::Collection::View>(entries->keySet()), processor);
    // BUG ? should return a result set of 4 entries but returns an empty set
    std::cerr<<"res size "<<res->size()<<std::endl;
    dumpMap(res->entrySet(), "res");
    // The job has be done correctly
    dumpCache(hCache, "putIfAbsent");
    std::cerr<<"== emulation delete where key in ('11', '===')"<<std::endl;
    cu::Set::Handle keys = cu::HashSet::create();
    keys->add(cl::String::View("11"));
    keys->add(cl::String::View("==="));
    cu::InvocableMap::EntryProcessor::Handle processor = cu::processor::ConditionalRemove::create(cu::filter::AlwaysFilter::getInstance(), true);
    cu::Map::View res = hCache->invokeAll(cl::cast<cu::Collection::View>(keys), processor);
    // BUG ? should return a result set of 2 entries but returns an empty set
    std::cerr<<"res size "<<res->size()<<std::endl;
    dumpMap(res->entrySet(), "res");
    // The job has be done correctly
    dumpCache(hCache, "delete where");
    std::cerr<<"== emulation delete where key like '2%'"<<std::endl;
    // should return entries as the corresponding flag is set to true
    cu::InvocableMap::EntryProcessor::Handle processor = cu::processor::ConditionalRemove::create(cu::filter::AlwaysFilter::getInstance(), true);
    cu::Filter::View f = cu::filter::LikeFilter::create(cu::extractor::KeyExtractor::create(), cl::String::create("2%"));
    cu::Map::View res = hCache->invokeAll(f, processor);
    // BUG ? should return a result set of 2 entries but returns an empty set
    std::cerr<<"res size "<<res->size()<<std::endl;
    dumpMap(res->entrySet(), "res");
    // The job has be done correctly
    dumpCache(hCache, "delete where2");
    int main(int argc, char** argv)
    try
    ch::CacheFactory::configure(ch::CacheFactory::loadXmlFile("client-cache-config.xml"));
    testInvokeAll();
    ch::CacheFactory::shutdown();
    catch(const cl::Exception::View &e)
    std::cerr<<"Ouch! "<<e<<std::endl;
    return 0;
    The output is:
    == init
    init: (11,v:11), (01,v:01), (25,v:25), (05,v:05), (21,v:21), (15,v:15),
    == emulation putIfAbsent
    res size 0
    res:
    putIfAbsent: (===,===MOD), (11,v:11), (01,v:01), (25,v:25), (+++,+++MOD), (05,v:05), (21,v:21), (15,v:15),
    == emulation delete where key in ('11', '===')
    res size 0
    res:
    delete where: (01,v:01), (25,v:25), (+++,+++MOD), (05,v:05), (21,v:21), (15,v:15),
    == emulation delete where key like '2%'
    res size 0
    res:
    delete where2: (01,v:01), (+++,+++MOD), (05,v:05), (15,v:15), The cache is modified as expected but the maps returned by invokeAll are always empty!
    Is it a bug? Do I understand the documentation incorrectly? Do I use the API incorrectly?

    Yes, I've noticed the difference between ConditionalPut and ConditionalPutAll. Ther constructor are:
    * Construct a ConditionalPut that updates an entry with a new value
    * if and only if the filter applied to the entry evaluates to true.
    * This processor optionally returns the current value as a result of
    * the invocation if it has not been updated (the filter evaluated to
    * false).
    * @param vFilter the filter to evaluate an entry
    * @param ohValue a value to update an entry with
    * @param fReturn specifies whether or not the processor should
    * return the current value in case it has not been
    * updated
    ConditionalPut(Filter::View vFilter, Object::Holder ohValue,
              bool fReturn = false);and
    * Construct a ConditionalPutAll processor that updates an entry with
    * a new value if and only if the filter applied to the entry
    * evaluates to true. The new value is extracted from the specified
    * map based on the entry's key.
    * @param vFilter the filter to evaluate all supplied entries
    * @param vMap a map of values to update entries with
    ConditionalPutAll(Filter::View vFilter, Map::View vMap);
    ConditionalPut has an extra flag for returning the new value. It does work with a call to invoke, I've tested it. Why can't we do the same with ConditionalPutAll? Do I have to N ConditionalPut instead of 1 ConditionalPutAll in order to know if my values have been updated?
    ConditionalRemove has the same flag than ConditionalPut:
    * Construct a ConditionalRemove processor that removes an
    * InvocableMap entry if and only if the filter applied to the entry
    * evaluates to true.
    * This processor may optionally return the current value as a result
    * of the invocation if it has not been removed (the filter evaluated
    * to false).
    * @param vFilter the filter to evaluate an entry
    * @param fReturn specifies whether or not the processor should
    * return the current value if it has not been removed
    ConditionalRemove(Filter::View vFilter, bool fReturn = false);But when used with invokeAll, it doesn't return any value as shown in the example I've sent. Is it a bug or a designed feature?

  • Working with collections in powershell

    Hi,
    I'm struggeling with collections in Powershell in general.
    I have a variable of type SPWebCollection created and want to add
    1) a single SPWeb - Object
    2) another collection of SPWeb - Objects
    Can someone tell me please why the following doesn't work:
    [Microsoft.Sharepoint.SPWebCollection]$allWebs += Get-SPWeb $URL1
    or this
    [Microsoft.Sharepoint.SPWebCollection]$allWebs += $site.AllWebs | Where-Object {$_.Url -like $URL2}
    Finally I want to empty the $allWebs collection i.e. remove all objects. How do I do that?
    I appreciate any feedback
    Thank you

    Hi,
    According to your description, you might want to gather all the SPWeb object into a collection object in order to delete all of them finally.
    As we can see, there is no such method in
    SPWebCollection object can meet you requirement, as a workaround, we can push all the SPWeb objects into an array, then operate
    these SPWeb objects in this array would do the trick.
    Here is a link about how to create a generic collection for a list of objects:
    http://www.andreasbijl.com/powershell-create-collections-of-custom-objects/
    More information about using collection in PowerShell:
    https://www.simple-talk.com/sysadmin/powershell/powershell-one-liners--collections,-hashtables,-arrays-and-strings/
    Best regards,
    Patrick
    Patrick Liang
    TechNet Community Support

  • Abstract Entity classes with Collections

    I trying to figure out a way to have a generics collection in a parent collection that can hold various entity types of the same super-class.
    One thing I've tried was the following:
    @Entity
    public class ParentEnt implements Serializable {
        private static final long serialVersionUID = 1L;
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;
        @Column
        private String parentName;
        @OneToMany(mappedBy="parentEnt")
        private Collection<ChildAbs> children;
        /* Methods removed */
    @Entity
    public abstract class ChildAbs implements java.io.Serializable {
        protected static final long serialVersionUID = 1L;
        @Id
        protected Long id;
        @ManyToOne
        protected ParentEnt parentEnt;
        /* Methods removed */
    @Entity
    public class ChildEnt extends ChildAbs implements Serializable {
        @Column
        protected String childName;
    }but this is the error I get:
    Exception [TOPLINK-30005] (Oracle TopLink Essentials - 2.0 (Build b58g-fcs (09/07/2007))): oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException
    Exception Description: An exception was thrown while searching for persistence archives with ClassLoader: sun.misc.Launcher$AppClassLoader@11b86e7
    Internal Exception: javax.persistence.PersistenceException: Exception [TOPLINK-28018] (Oracle TopLink Essentials - 2.0 (Build b58g-fcs (09/07/2007))): oracle.toplink.essentials.exceptions.EntityManagerSetupException
    Exception Description: predeploy for PersistenceUnit [testPU] failed.
    Internal Exception: Exception [TOPLINK-7250] (Oracle TopLink Essentials - 2.0 (Build b58g-fcs (09/07/2007))): oracle.toplink.essentials.exceptions.ValidationException
    Exception Description: [class test.ParentEnt] uses a non-entity [class test.ChildAbs] as target entity in the relationship attribute [private java.util.Collection test.ParentEnt.children].So, it looks like there is no way to have a generics collection for an abstract entity class. Is there another way to accomplish what I want using a generics collection?
    Additionally, entity ChildEnt generates an error due to the abstract class' id property not carrying forward (see Abstract Entities: http://java.sun.com/javaee/5/docs/tutorial/doc/bnbqa.html#bnbqo)
    Exception Description: Entity class [class testprintservices.ChildEnt] has no primary key specified. It should define either an @Id, @EmbeddedId or an @IdClass.Any input would be appreciated.

    As far as my first question, I was trying to make my collection so it can hold various type of entity classes, but now that I think about it, it was a bad idea. For instance, being able to hold ChildEnt and ChildEnt2 in the same collection. If JPA did allow this, it might be possible to save the entities to the DB, but the reverse wouldn't be possible.
    Ok, regarding my 2nd question: I don't understand why having it as @Entity wouldn't. The links (mine and yours) clearly shows that @Id is carried forward in the example they provide. Anyway, since I can't use the superclass in the collection, this is pointless. I'll use the suggested annotation.
    Thanks.

  • One thing java generics are missing

    specialization!
    I'll give you a templated example with a function here:
    template <typename T>
    inline std::string to_string(const T& t)
    std::istringstream ss;
    ss << t;
    return ss.str();
    that's one of those standard conversion snippets that everyone uses... as long as T supports the "<<" operator, it will convert just fine...
    Now, if you're using this function in other template based code, the problem comes up:
    template <typename T>
    void foo(const T& t)
    std::string s = to_string(t);
    ... do something with s now...
    it makes sense, if you want to do operations with a string... but what if the type T *was* a string... the to_string function just did a whole mess of needless operations (stringstream conversion)...
    here comes template specialization to the rescue:
    template <> inline std::string to_string<std::string>(const std::string& t)
    return t;
    there we go... no extra steps... because it's inlined to begin with, the compiler will remove it... (this is what's called a conversion shim).  Now when the to_string function is called with an std::string argument, it does nothing.

    Hmmm, it seems I didn't explain it too well:
    the 3rd snippit is the same as the first, however the "typename T" has been removed and all instances of "T" have been replaced with a specific type: this is template specialization... it allows for you to have different code for each type... it's a complicated form of function overloading....
    what I'm saying is that, in a java generic collection, you may have all this code that works for all types, but could be optimized for one of those types... I used string above...
    for instance... let's say there's a member function to count the number of characters used if the type were converted to a string... the easiest thing to do would be to convert it to a string an get the length.... however, in the case of numbers, there's a much, much more efficient way to do it (can't recall the algorithm... but you can get the number of digits with division and maybe a log10 or something...)... this is a mundane case, but even if you did want to use that math for the int version of that generic, you couldn't...

Maybe you are looking for