A Generic Class is Shared by all its Invocations

hello all,
i am not understanding what this means
all instances of a generic class have the same run-time class, regardless of their actual type
i am taking this to mean that no matter how many instances of list i create underneath it all 1 class is actually holding all my data for all instances. is this correct?
maybe i am not clear on the definition of a runtime class.
how does this affect my programming? will calling static methods on one instance affect the others?
i am confused
thanks
ed

i am not understanding what this means
all instances of a generic class have the same
run-time class, regardless of their actual typeInstances of the generic class ArrayList<E> could be for example ArrayList<Integer>, ArrayList<String>, or ArrayList<Date>. What the phrase above means is that, although the actual type of these instances is different (the types contained in the list are different), at run-time (when your program executes), they are still of the same class, namely ArrayList. This is because the compiler removes all references to the types at compile time (called type erasure). So, an ArrayList<Integer> is not another class than ArrayList<String>.
i am taking this to mean that no matter how many
instances of list i create underneath it all 1 class
is actually holding all my data for all instances. is
this correct?This is not correct. That instances of generic types have the same run-time class is not related to the data the instances contain. As mentioned by Malvolio, only static data is contained in the class (and hence shared among instances). Instance data is stored in the instance and hence can be different for every instance of a class. But this is true for all kinds of classes, not only generic ones.
how does this affect my programming? will calling
static methods on one instance affect the others?If the static method modifies static data of the class, this will affect other instances since static data is shared by all instances of a class. But again, this holds for all kinds of classes, not only generic ones.
i am confusedHope you�re not anymore.
Cheers
Matthijs

Similar Messages

  • Generic class for deep cloning

    How can I write generic class for deep cloning instead of implementing cloneable for each and every object

    Yes, probably you'd need to use reflection. Though, generic deep copy brings up some issues not readily resolvable at run-time, such as, for example, does the object you want to copy refer to a shared or synchronized resource, such as a db connection? If so, by making a new, say, DBConnection object, you then take up a db connection that you really don't need or want to take up (db conns being scarce in many I.T. shops that own a limited number of Oracle or SQL Server, etc. db conn. licenses). Also, many classes these days are getting written that use "obj = classname.newInstance()" (with their constructors made private so you can't use "new SomeObject()") instead of the more commonsense and traditional "obj = new SomeObject()". [Hey, can anyone explain why it might be preferable to use "classname.newInstance()" at times over "new SomeObject()"?  I can't to this day tell why it might be better or why some hacks have started doing this.]
    I am not saying either that you couldn't do it or that you shouldn't. In fact, if you wrote a really good generic deep copy class, it may very well suit your needs 95+% of the time. It'd be a great programming exercise that would likely result in something very useful to someone somewhere (yourself included), and would get you to really learn the reflect package, time generally well-spent. I also can see how it'd be a great exercise in writing recursive calls (if for example you'd like no limit to the depth of objects created within your deep-copied object). You may need to supply a few caveats for use, such as that there's no guarantee that objects within the object to be copied that don't have public constructors can be copied, and that objects that hold other objects that are limited in availablity due to their very natures, such as db connections, may not get fully copied. Another one may be that no object can be copied as long as a thread created and run from it is executing at the time the copy is done (because you couldn't guarantee the to-be-copied object instance's data or object reference state), or that perhaps in some cases, certain kinds of method-level (ie, what's officially called by Sun, "automatic") variables declared and used within, for example, blocks of code within methods, may not have their values copied correctly if they are not visible to the reflect pkg objects (though I'd have to look into that one myself to be sure it would be an issue).
    Doing a search on "deep copy" or "deep clone" on java.sun.com as well as on the 'net reveals surprisingly little except suggestions for using object serialization to do all the dirty work for you.
    I am surprised there isn't a kind of virtual working group trading ideas on the topic and trying collaboratively to come up with a good, solid generic deep copy class as a public service for all the Java brethren. Does anyone know of one? And if not, wanna start one?

  • Using static .values() method of Enum in Generic Class

    Hi *,
    I tried to do the following:
    public class AClass<E extends Enum<E> >  {
         public AClass() {
              E[] values = E.values(); // this DOESN'T work
              for (E e : values) { /* do something */ }
    }This is not possible. But how can I access all Enum constants if I use
    an Enum type parameter in a Generic class?
    Thanks for your help ;-) Stephan

    Here's a possible workaround. The generic class isn't adding much in this case; I originally wrote it as a static method that you simply passed the class to:
    public class Test21
      public static enum TestEnum { A, B, C };
      public static class AClass<E extends Enum<E>>
        private Class<E> clazz;
        public AClass(Class<E> _clazz)
        {  clazz = _clazz;  }
        public Class<E> getClazz()
        {  return clazz;  }
        public void printConstants()
          for (E e : clazz.getEnumConstants())
            System.out.println(e.toString());
      public static void main(String[] argv)
        AClass<TestEnum> a = new AClass<TestEnum>(TestEnum.class);
        a.printConstants();
    }

  • Hp LaserJet 1200 Generic Class: Waiting for device

    I have 2 computers that I want to print to my hp Laserjet 1200 printer. We are using an iogear 4-port usb 2.0 sharing switch. One computer prints fine but the other always displays a message "Generic Class: Waiting for device." Help!

    Both computers have the printer driver installed. The usb device does not have a driver to install. You just plug in the usb cords to each computer and the printer. You only install a driver if using a pc operating system.

  • What is the use of Generic class in java

    hi everyone,
    i want to know that
    what is the use of Generic class in java ?
    regards,
    dhruvang

    Simplistically...
    A method is a block of code that makes some Objects in the block of code abstract (those abstract Objects are the parameters of the method). This allows us to reuse the method passing in different Objects (arguments) each time.
    In a similar way, Generics allows us to take a Class and make some of the types in the class abstract. (These types are the type parameters of the class). This allows us to reuse the class, passing in different types each time we use it.
    We write type parameters (when we declare) and type arguments (when we use) inside < >.
    For example the List class has a Type Parameter which makes the type of the things in the list become abstract.
    A List<String> is a list of Strings, it has a method "void add(String)" and a method "String get(int)".
    A List<File> is a list of Files, it has a method "void add(File)" and a method "File get(int)".
    List is just one class (interface actually but don't worry about that), but we can specify different type arguments which means the methods use this abstract type rather than a fixed concrete type in their declarations.
    Why?
    You spend a little more effort describing your types (List<String> instead of just List), and as a benefit, you, and anyone else who reads your code, and the compiler (which also reads your code) know more accurately the types of things. Because more detail is known, the compiler is able to tell you when you screw up (as opposed to finding out at runtime). And people understand your code better.
    Once you get used to them, its a bit like the difference between black and white TV, and colour TV. When you see code that doesn't specify the type parameters, you just get the feeling that you are missing out on something. When I see an API with List as a return type or argument type, I think "List of what?". When I see List<String>, I know much more about that parameter or return type.
    Bruce

  • XI: How To Use JAVA generic Class to  perform SAP data Lookup........

    Hello All,
    I want to create a generic class which is used to perorm SAP data lookup.
    I don't want to use Jco or RFC channel..
    Is there any other way to do this?
    waiting for Reply 
    thank in advance.
    - AKSHAY.

    Hi,
    use RFC channel
    you can wrap it up like this:
    /people/morten.wittrock/blog/2006/03/30/wrapping-your-mapping-lookup-api-code-in-easy-to-use-java-classes
    why do you want to create something diffucult to maintin and non standard if
    you can use the RFC API ?
    Regards,
    michal
    <a href="/people/michal.krawczyk2/blog/2005/06/28/xipi-faq-frequently-asked-questions"><b>XI / PI FAQ - Frequently Asked Questions</b></a>

  • Javaagent and class data sharing with Java 6.0

    Hi,
    I'm trying to use instrumentation (using the -javaagent) but
    I noticed that when I run the my application with JDK 1.6 it loads all system
    classes from the "shared objects file" and the transformer has no chance to run.
    With JDK 1.5 it works fine, as well as in debug mode of JDK 1.6.
    Is this normal or it is a bug? If it is normal, how should I instrument the system classes?
    Thanks in advance,
    Genady

    I just found that the reason it was working for me with JDK 1.5 is that my classes.jsa file was corrupted for some reason.
    So the behavior is consistent for both JDK 1.5 and 1.6.
    I also found that if I add
    Can-Redefine-Classes: true to the manifest (even if I don't do any class redefinitions) it causes the class data sharing to be disabled.
    This workaround is good enough for me.
    Genady

  • Support for generic classes

    hi,
    i m using creator 2 update 1, it does not support generic classes.
    it says use source 1.5 for generic classes.
    please tell me how to solve this problem
    thank you

    Well, not necessarily true... Most of the latest graphics cards work off of a common core, which is named depending on its maximum tested performance and on how many pipelines passed quality checks.
    Thus a 7300 is fundementally identical to a 7800, except that it uses fewer fragment/vertex pipelines and is clocked lower. This is done either artificially by disabling parts of the GPU, or if when they fail quality control.
    Either way, the drivers are the same, and have been unified for a long time for the entire product line. In fact if you look at the drivers for the card in yoru computer you will see they are more then likely for a different chipset. My MBP claims the drivers are for a X1000, even though the card is a X1600.

  • HT5527 I have had my storage reduced once already.  In the process they removed my "Save" mailbox and all its contents.  I do notcare about contents so much as starting a new Save box.  How?  (OS X 10.7.5)

    My iCloud storage is being reduced.  I have already had it reduced once.  In the process they removed my "Save" mailbox and all its contents.  (One would think that that would be the last thing they removed.  But they took that and the "Trash" mailbox, yet left several thousand old and read messages which were in my "Inbox".)  I do not expect to get the "Save" contents back, but I would like to restore the "Save" mailbox, so that I can start from scratch saving msgs in it again.  But I cannot figure out how to do that.  When I go to "Mailbox" on the top line (between View and Message) and select New Mailbox I get a dialog box in which I can name a new mailbox.  When I type Save, for the name of the new Mailbox I get a response; "The mailbox 'Save" already exists."  But I cannot find it.
    Thanks,  Bill Burner

    Option 1
    Back Up and try rebuild the library: hold down the command and option (or alt) keys while launching iPhoto. Use the resulting dialogue to rebuild. Choose to Repair Database. If that doesn't help, then try again, this time using Rebuild Database.
    If that fails:
    Option 2
    Download iPhoto Library Manager and use its rebuild function. (In Library Manager it's the FIle -> Rebuild command)
    This will create an entirely new library. It will then copy (or try to) your photos and all the associated metadata and versions to this new Library, and arrange it as close as it can to what you had in the damaged Library. It does this based on information it finds in the iPhoto sharing mechanism - but that means that things not shared won't be there, so no slideshows, books or calendars, for instance - but it should get all your events, albums and keywords, faces and places back.
    Because this process creates an entirely new library and leaves your old one untouched, it is non-destructive, and if you're not happy with the results you can simply return to your old one. 
    Regards
    TD 

  • How to print a dialog box with all its components ?

    Hi !
    I've written an application.It has a dialog box [JDialog] containing following components:
    1) 2 JLabels.
    1) A JTextField.
    3) A JTable with some values.
    4) A JProgressBar.
    5) A JButton.
    6) An animated gif image.
    I want to print the dialog box with all its components exactly as the are [ Except the button & animated gif ].
    Would anybody please help me?
    My Operating System: Windows XP

    The article over at http://java.sun.com/developer/technicalArticles/Printing/Java2DPrinting/ has some helpful information on printing Swing components.
    It suggests creating a subclass of the JComponent that you want to print, and have it implement Printable interface.
    So, something like (note, uncompiled / untested code alert) :
    import java.awt.Frame;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.HeadlessException;
    import java.awt.print.PageFormat;
    import java.awt.print.Printable;
    import javax.swing.JDialog;
    public class PrintableDialog extends JDialog implements Printable {
          * Or whichever constructor you need...
         public PrintableDialog(Frame owner, String title, boolean modal) throws HeadlessException {
              super(owner, title, modal);
          * Implementation of the Printable interface.
           public int print(Graphics g, PageFormat pf, int pageIndex) {
              if (pageIndex != 0) return NO_SUCH_PAGE;
              Graphics2D g2 = (Graphics2D) g;
              g2.translate(pf.getImageableX(), pf.getImageableY());
              getContentPane().paint(g2);
              return PAGE_EXISTS;
    }Cheers,
    John

  • Extending a generic class

    hi all,
    i want to extends a generic class, HashTable<K,V> to be concrete , but i want my class would be in use as MyHashTable<String, String>
    does any one know the syntax for that ??
    what i actually mean is how do i set the generics data types in the inheritance mechanism ??
    thanks
    Jaimon

    hi all,
    i want to extends a generic class, HashTable<K,V> to
    be concrete , but i want my class would be in use as
    MyHashTable<String, String>
    does any one know the syntax for that ??
    what i actually mean is how do i set the generics
    data types in the inheritance mechanism ??So, you want your MyHashTable to not be generic, but always be a Hashtable<String, String>? The syntax is the same as everywhere.
    class MyHashtable extends Hashtable<String, String> {
    }Or do you want your MyHashtable to be generic, as in:
    class MyHashtable<K, V> extends Hashtable<K, V> {
    }

  • Need help with generic class with comparable type

    Hi. I'm at University, and I have some coursework to do on writing a generic class which offers ordered binary trees of items which implement the comparable interface.
    I cant get the code to compile which I have written.
    I get the error: OBTComparable.java uses unchecked or unsafe operations
    this is the more detailed information of the error when I compile with -Xlint:unchecked
    OBTComparable.java:62: warning: [unchecked] unchecked call to insert(OBTType) as
    a member of the raw type OBTComparable
    left.insert(insertValue);
    ^
    OBTComparable.java:64: warning: [unchecked] unchecked call to insert(OBTType) as
    a member of the raw type OBTComparable
    right.insert(insertValue);
    ^
    OBTComparable.java:75: warning: [unchecked] unchecked call to find(OBTType) as a
    member of the raw type OBTComparable
    return left.find(findValue);
    ^
    OBTComparable.java:77: warning: [unchecked] unchecked call to find(OBTType) as a
    member of the raw type OBTComparable
    return right.find(findValue);
    ^
    and here is my code for the class
    public class OBTComparable<OBTType extends Comparable<OBTType>>
      // A tree is either empty or not
      private boolean empty;
      // If the tree is not empty then it has
      // a value, a left and a right.
      // These are not used it empty == true
      private OBTType value;
      private OBTComparable left;
      private OBTComparable right;
      // Create an empty tree.
      public OBTComparable()
        setEmpty();
      } // OBTComparable
      // Make this tree into an empty tree.
      private void setEmpty()
        empty = true;
        value = null; // arbitrary
        left = null;
        right = null;
      } // setEmpty
      // See if this is an empty (Sub)tree.
      public boolean isEmpty()
      { return empty; }
      // Get the value which is here.
      public OBTType getValue()
      { return value; }
      // Get the left sub-tree.
      public OBTComparable getLeft()
      { return left; }
      // Get the right sub-tree.
      public OBTComparable getRight()
      { return right; }
      // Store a value at this position in the tree.
      private void setValue(OBTType requiredValue)
        if (empty)
          empty = false;
          left = new OBTComparable<OBTType>(); // Makes a new empty tree.
          right = new OBTComparable<OBTType>(); // Makes a new empty tree.
        } // if
        value = requiredValue;
      } // setValue
      // Insert a value, allowing multiple instances.
      public void insert(OBTType insertValue)
        if (empty)
          setValue(insertValue);
        else if (insertValue.compareTo(value) < 0)
          left.insert(insertValue);
        else
          right.insert(insertValue);
      } // insert
      // Find a value
      public boolean find(OBTType findValue)
        if (empty)
          return false;
        else if (findValue.equals(value))
          return true;
        else if (findValue.compareTo(value) < 0)
          return left.find(findValue);
        else
          return right.find(findValue);
      } // find
    } // OBTComparableI am unsure how to check the types of OBTType I am comparing, I know this is the error. It is the insert method and the find method that are causing it not to compile, as they require comparing one value to another. How to I put the check in the program to see if these two are of the same type so they can be compared?
    If anyone can help me with my problem that would be great!
    Sorry for the long post, I just wanted to put in all the information I know to make it easier for people to answer.
    Thanks in advance
    David

    I have good news and undecided news.
    First the good news. Your code has compiled. Those are warnings not errors. A warning is the compiler's way of saying "I understand what you are asking but maybe you didn't fully think through the consequences and I just thought I would let you know that...[something] "
    In this case it's warning you that you aren't using generics. But like I said this isn't stopping it from compiling.
    The undecided news is the complier is warning you about not using generics. Are you supposed to use generics for this assignment. My gut says no and if that's true then you have no problem. If you are supposed to use generics well then you have some more work.

  • Multiple inherited with generics classes

    Hello all, here is my generic observer/ subject code.
    package jstock;
    * @author yccheok
    public interface Observer<S, A> {
        public void update(S subject, A arg);
    public class Subject<S, A> {
        public void attach(Observer<S, A> observer) {
            observers.add(observer);
        void notify(S subject, A arg) {
            for (Observer<S, A> obs : observers) {
                obs.update(subject, arg);
        private List<Observer<S, A>> observers = new CopyOnWriteArrayList<Observer<S, A>>();
    }However, when I try to implements more than one class (single class only is ok), I get the following error :
    /home/yccheok/Projects/jstock/src/org/yccheok/jstock/gui/MainFrame.java:40: org.yccheok.jstock.engine.Observer cannot be inherited with different arguments: <org.yccheok.jstock.engine.RealTimeStockMonitor,java.util.List<org.yccheok.jstock.engine.Stock>> and <org.yccheok.jstock.engine.StockHistoryMonitor,org.yccheok.jstock.engine.StockHistoryServer>
    public class MainFrame extends javax.swing.JFrame implements
    Here is the code which I am implementing the generic classes.
    public class MainFrame extends javax.swing.JFrame implements
    org.yccheok.jstock.engine.Observer<RealTimeStockMonitor, java.util.List<org.yccheok.jstock.engine.Stock>>,
    org.yccheok.jstock.engine.Observer<StockHistoryMonitor, StockHistoryServer>
    May I know how I can avoid the error message?
    Thank you.
    cheok

    However, when I try to implements more than one classMore than one interface, you mean.
    May I know how I can avoid the error message?You can't implement a generic interface more than once.
    http://angelikalanger.com/GenericsFAQ/FAQSections/ProgrammingIdioms.html#Can%20a%20class%20implement%20different%20instantiations%20of%20the%20same%20parameterized%20interface?

  • Class Data Sharing in Java 5

    Hi All,
    I am looking at porting over our current Java application from Java 1.4.2 to Java 1.5.
    One of the main reasons is because of the CDS facility in Java 1.5.
    Running the same app, one on 1.4.2 and the other on 1.5, on 1.5 it uses about 20% more memory !!!!
    This application involves 3 JVM's running communicating via RMI.
    When I start each of the applications with -Xshare:on, the first starts fine, indicating it is using CDS,
    (-showversion parameter will indicate sharing), but then the next two wont start giving an error indicating
    the shared archive cannot be accessed.
    Before I started the apps I manually created the shared archive using the call java -Xshare:dump which
    places the classes.jsa file in the directory jre/lib/i386/client/classes.jsa
    I am running an Intel Solaris platform.
    Any ideas why this isnt working ?

    ok, I have some more information after doing more investigation...
    Here is the bug which I submitted to Sun...
    FULL OS VERSION :
    SunOS con1 5.8 Generic_108529-29 i86pc i386 i86pc
    A DESCRIPTION OF THE PROBLEM :
    I am running an application with 3 JVM's. I have manually enabled Class Data Sharing using the command java -Xshare:dump. This seems to work fine.
    When I start the first JVM with the command line option -Xshare:on it seems to start fine and indicates "sharing" when I print out -showversion.
    Then when I start any subsequent JVM's with -Xshare:on AND the -Xmx5m parameter I receive the following error:
    An error has occured while processing the shared archive file. Unable to reserve shared region. Error occurred during initialization of VM Unable to use shared archive.
    It seems to work fine if I dont set the maximum heap size.
    THE PROBLEM WAS REPRODUCIBLE WITH -Xint FLAG: No
    THE PROBLEM WAS REPRODUCIBLE WITH -server FLAG: No
    STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
    Try to execute a JVM with class data sharing on, then try it again with class data sharing on, AND trying to set the maximum heap size.
    EXPECTED VERSUS ACTUAL BEHAVIOR :
    It should still allow CDS.
    ERROR MESSAGES/STACK TRACES THAT OCCUR :
    An error has occured while processing the shared archive file. Unable to reserve shared region. Error occurred during initialization of VM Unable to use shared archive.
    REPRODUCIBILITY :
    This bug can be reproduced always.
    The error only occurs when using Xshare AND Xms<NUMBER>m as parameters !

  • Convert instance of generic class in byte[]  ?

    Hello i need the method for convert instance of a generic class in byte[]
    I have already tried this method but it does not work with all the classes
    often the execption class not serializzabile is generated.
    ByteArrayOutputStream regStore = new ByteArrayOutputStream();
    ObjectOutputStream regObjectStream = new
    ObjectOutputStream(regStore);
    regObjectStream.writeObject(myGenericClass );
    byte[] bbyte = regStore.toByteArray();

    I have needs to convert in byte[ ] the istance class present in memory
    the is javax.media.Buffer
    in tried this method but not function ( exception not serialize is generated)
    frameGrabber = (FrameGrabbingControl) player.getControl("javax.media.control.FrameGrabbingControl");
    Buffer buf = frameGrabber.grabFrame();
    ByteArrayOutputStream regStore = new ByteArrayOutputStream();
    ObjectOutputStream regObjectStream = new ObjectOutputStream(regStore);
    regObjectStream.writeObject( buf.getClass() );
    byte[] bbyte = regStore.toByteArray();

Maybe you are looking for