Arraylist polymorphism concept

Can you please explain why both the below statements compile? Animal is the superclass and Dog the subclass.
I am not able to understand the meaning of the statement even.
ArrayList<Dog> dogs1 = new ArrayList<Animal>();
ArrayList<Animal> animals = new ArrayList<Dog>();

Mehta wrote:
Head First Java 2nd edition Page No. 579 says it should compile. Even i am not able to compile.
Any comments....Seeing is believing. If you try to compile the exact same code, and it doesn't compile, then obviously, it doesn't compile. No matter what the book says.

Similar Messages

  • Polymorphism

    Hai All
    I hava doubt regrading polymorphism concept . Firstly please look in to this program then explain me clearly
    class Shape
    protected Color color;
    protected int x, y;
    Shape (Color c, int xPosition, int yPosition)
    color = c;
    x = xPosition;
    y = yPosition;
    } // constructor
    public void drawShape (Graphics g)
    g.setColor (color);
    g.drawString ("Shape", x, y);
    } // method drawShape
    } // class Shape
    class Circle extends Shape
    private int radius;
    Circle (Color c, int x, int y, int r)
    super (c, x, y);
    radius = r;
    } // constructor
    public void drawShape (Graphics g)
    g.setColor (color);
    g.fillOval (x, y, 2*radius, 2*radius);
    } // method drawShape
    } // class Circle
    class Rectangle extends Shape
    private int width, height;
    Rectangle (Color c, int x, int y, int w, int h)
    super (c, x, y);
    width = w;
    height = h;
    } // constructor
    public void drawShape (Graphics g)
    g.setColor (color);
    g.fillRect (x, y, width, height);
    } // method drawShape
    } // class Rectangle
    if i want to access Circle drawShape method i can do like this :
    Circle ob=new Circle();
    ob.drawShape();
    likewise i can access Rectangle drawShape method i can do like this :
    Rectangle ob=new Rectangle ();
    ob.drawShape();
    instead of doing , some one trying to access some this way
    Shape ob=new Rectangle();
    Rectangle rectangle=(Rectangle)ob;
    rectangle.drawShape();
    Circle circle=(Circle)ob;
    circle.drawShape();
    please explain me what exact different between this two way . i hava been trying to find exact solution for this but i am not able .
    Thanks
    Selvakumar

    I don't know what your question is. The following are the same.
    Circle c = new Circle(...);
    c.drawShape(g);
    Shape shp = new Circle(...);
    shp.drawShape(g);..because in both cases you are sending the same object the same message: draw yourself!

  • How to access a nested child tag values in  XML Object(getting error:No Such variable)

    Hi,
    I could see the XML object data and while accessing a perticular attribute let say "SlotA"  it is showing "No such variable Error".
    I appreciate any of your  inputs or suggestions to solve this error.
    You can find the screen snapshot of the problem as part of the attachment here.
    Thanks in advance
    CSNPrasad.

    Dear Natasha,
    Thanks for your mails & cooperation as well.
    This time i  have added the trace() and can see the value.Now the problem is "can't access a property or method of a null object reference"
    Noe: This code mxml file is called at Runtime based on the data defined in the XMLSocket data.
    I need to display Remote devices like davice1,device2 device3 etc. these are added/delete at any time ,so we need to show same changes in UI at Runtime.
    I implemented Polymorphism concept to construct the device object at runtime like follows
    var device:Object;
    for each (var deviceData:XML indeviceListXML..Device)
                        device = getBatteryBay(deviceData.deviceId)
                        // If device already exists with the deviceId, update the details
                        // Else create a newdevice and add it to the container for displaying it.
                                                                                    if (device == null)
                            if (device.Type == "DEVICE1")
                                device = new Device1();
                            else if (device.Type == "DEVICE2")
                            device = new Device2();
                            else
                                device = new DefaultDevice();
                            device.id = deviceData.deviceId;
                          device.name = deviceData.devicename;
                         device.setData(deviceData);
    Here new Device1(); and new Device2() are the UIComponents and created at Runtime, upto here no problem to display, when i try to setData to the devices it is throwing error
    "can't access a property or method of a null object reference". because Device1 and Device2 has Child components like "DataIndicator" and need to set properties to these components which are not created yet.
    I appreciate any of your Input or suggestions at the earliest
    Thanks in Advance
    Regards

  • Quesion on fragile base problem

    Hi,
    I like to know how JAVA addesses the fragile base problem. I understand fragile base problem occurs when you want to add a new feature to a base programs, it requires the modification of all the children class to also inherit the new feature. This takes a lot of effort and it's error prone. I kind of know that polymorphism concept is the feature Java added to address the problem but I don't have a solid picture of how it handles the problem. Can anyone provide some info on this. Thanks.

    Sorry, I probably did not mean adding new features. I
    think what I am trying to say is supposedly we change
    a method in the parent class to return a String,
    previously a Integer. If we don't retrofit the
    children class, it will cause the program to fail
    compiling. If the program uses deep inheritance, just
    one single change might require a lot of work to
    retrofit. So, how would a developer design the
    application to avoid this problem? Unless you are overriding or extending the method this isn't the case. Really it's not so much a parent - child problem as it is a general application problem. Everywhere you are calling this method will no longer compile.
    One solution that always works is to make the change and let the compiler tell you what other code needs to be fixed. Java doesn't have any answers for this problem though some IDEs do as the previous poster mentioned.
    The best way to avoid something like this is to have a good design. I can't think of any good examples of when this could happen. Usually deeply inherited classes should be almost completely stable. If not, maybe that method should't be part of the base class at all. Changing a method to return a String instead of an Integer is a huge change. Really you are talking about changing its purpose. Maybe if you gave a better example I could understand a little better.

  • Concept of Abstraction and Polymorphism

    Hi friends,
    I'm just new to Java.I studied a little bit of C, I'm currently studing VB and Java.
    There are one or two concepts in Java that are very hard to grasp for me.
    The first is abstraction and the second is polymorphism.
    Can anybody outline to me in simple words(use simple example if needed)what those 2 concepts are all about?
    Thanks a lot
    Marco

    In your example, you could make Vehicle an abstract
    class. You can't simply have a vehicle, but you can
    have a car which IS a vehicle. In your abstract class
    Vehicle, you might define an abstract method public
    int getSeats() (you want it to be abstract because it
    changes from one type of vehicle to the next). So the
    class Car extends Vehicle, overrides the method
    getSeats() and returns 5. The class Ute extends
    Vehicle, overrides the method getSeats() and returns 2
    (you might make a SuperCabUte that extends Ute and
    returns 5, or whatever).Radish is right,
    Think of it as modelling of real life. You would generalise the description of your car as a Vehicle (abstraction, which can be implemented as an interface in Java) where in fact you own a car
    Similarly you can have an inteface called RealEstate where in fact you own a TwoStoreyHouse ( a class that implements the RealEstate interface)
    the interface can describe the general 'characterstics' of real estate properties ie land size, council rates etc.
    HTH...hey....

  • Very Basic..  Array list Concept.. using two arraylist..

    Hello all,
    Please clear my Arraylist concept.. the problem is that I am using two arraylist one.. in Spriteframe, and other in SpriteFramecollection.. and adding objects to them..
    the problem comes when am adding new frame to framecollection.. instead of adding new.. it changes all previous frames too.. I want to reflect change only in latest one..
    Lets explain me in detail..
    I have used like
    class Project..
         ---> Calculate Button
         ---> MultipleMove Button
         ---> Save Button
    In Calculate class..
         Sprite st = new Sprite();
         SpriteFrame sframe = new SpriteFrame();
         ..// I do some calculation
         st.newSprite(croppedimage, file, 0, 0, number, 0, 0);         //here am creating sprite
         sframe.addSprite(st);                            //here am adding sprite to Spriteframe
    In MultipleMove class..
         SpriteFrame sframe = new SpriteFrame();
         // do some adding and deleting of sprites in frame
    In save class..     //Problem comes here.. Am going crazy!!
         SpriteFrameCollection sframecoll = new SpriteFrameCollection();
         SpriteFrame frame = new SpriteFrame();
    --->     sframecoll.addSpriteFrame(frame);     <------- // am just adding frame to framecollection
         }Now when I am printing elements of Sprite.. frame1, and frame2 gets changed simultaneously.. I mean why frame1 also gets changed..
    am just adding new SpriteFrame.. to spriteframecollection..
    please someone tell me what is wrong in my concept of understanding arraylist..
    as making class objects again and again wrong..
    what should I do to add only newly Frame to framecollection??.. why all previous frame gets changed too.. ??
    gervini
    I have class Sprite, SpriteFrame, SpriteFrameCollection as shown below..
    import java.io.*;
    import java.awt.Image;
    public class Sprite               // Each single sprite
         Image img;
         File file;                 // is filepath where this sprite is located
         int xcord,ycord;           // xcoord,ycoord are real position in frame
         int numberinfile;           // this is the position of the sprite in the raw file
         int mirrorh, mirrorv;      // for normal=00,horizontal=10,vertical=01,both=11
         void newSprite(Image img, File file, int xcord, int ycord, int numberinfile, int mirrorh, int mirrorv)
              this.img = img;
              this.file = file;
              this.xcord = xcord;
              this.ycord = ycord;
              this.numberinfile = numberinfile;
              this.mirrorh = mirrorh;
              this.mirrorv = mirrorv;
    import java.io.*;
    import java.util.*;
    public class SpriteFrame                          // Full One Frame consisting of many sprites..
         static ArrayList spritelist = new ArrayList();               // arraylist containing many sprites
         void addSprite(Sprite sprite)
             spritelist.add(sprite);                              
        void removeSprite(Sprite s)
             spritelist.remove(s);
    import java.io.*;
    import java.util.*;
    public class SpriteFrameCollection                    // Consisting of many frames..
         static ArrayList spriteframelist = new ArrayList();          // Arraylist of many frames
         void addSpriteFrame(SpriteFrame spriteframe)
              spriteframelist.add(spriteframe);
        void removeFrame(SpriteFrame sf)
             spriteframelist.remove(sf);
    }

    It is hard to see what it coursing your problems becouse you only posted axtracts from your code. However I think that it is becouse every time you want to access the methods in SpriteFrame you ar creating a new object. Every time you create a new Strite fram a new, empty ArrayList is being created. What you want to do is create this only once, and pass this instance to the parts of your code that need it.
    Let me try to explain this using a matphor. 2 people are trying to make some tea. One person has access to water and another has access to teabags. Both of them know that there is such a thing as a kettle. What you are doing is; person 1 is creating a kettle and filling it with water. Then person 2 is creating a new kettle and trying to pour the water from it. obviously this doesn't work. You want person 1 to creat a kettle, fill it with water and then pass that kettle to person 2. person 2 takes this kettle and then pours the water from it.

  • Is polymorphism a bad design for object oriented concept?

    i think polymorphism is bad concept for object oriented concept..having the same name with different parameter function ..according to my opinion may constitue in efficient skill in programming..instead if using the same name why we cannot use different name...for example each human being will have have unique characterstics..(i.e each persons DNA would be different..)so why can't we have different function names.. even if u choose a username to create a new account it would not support same names..i think it is confusing .. i think this concept is lessly used in modern programming usage... as it has less usage i think the future language designs should not support polymorphism..
    i just want to know ur opnions..

    Is it just me or did Sun fuck up the posting screens?I didn't notice anything; care to enlighten me?800-pixels-wide window and still a vertical scrollbar, but, to make up for
    that, 250 pixels of unused whitespace to the left. And the search text
    field is still unnamed.I agree with that rediculously wide left margin, i.e. rearranging some of
    those things would allow for a better screen estate usage. But didn't Sun
    already give us that crap in a previous incarnation of their mannah?
    Besides that, I still don't notice any difference ...
    kind regards,
    Jos (<--- call me a silly ignoramus)

  • ArrayList concept

    Hi,
    I know how to add elements in ArrayList,
    My requirement is
    ArrayList al=new Arraylist();
    al.add(12);//this is my requirement i need code for these method can u able to send successful code.
    I know we can add like this
    al.add(new Float(12.090909));
    but I need add(12);

    ArrayList al=new Arraylist();
    al.add(12);//this is my requirement i need code for
    these method can u able to send successful code.If I am allowed to take this very literally, I can solve your problem. Declare a class Arraylist (with a lowercase l) that extends ArrayList (which has a capital L) and provide a method add(int). You're done.
    That was intended to be a joke!
    Seriously, either box your int into an Integer before adding to the ArrayList, or write your own int list class. The latter may or may not use ArrayList for implementation, either through inheritance or composition. Only, give it a descriptive name, list IntArrayList, for example.

  • Passing polymorphic ArrayLists to a method expecting ArrayList superclass

    In short, is it possible? In keeping in line with my other threads and a program using cats, I give you this example using Cats and Animals (a cat is an animal):
    public void go()
         ArrayList<Cat> lotsOfCats = new ArrayList<Cat>();
         feed(lotsOfCats);
    void feed(ArrayList<Animal> animals)
         //feed the animals
    }So an error is thrown because the function is expecting an ArrayList of Animals and I'm trying to pass in an ArrayList of Cats. The function shouldn't have any problem dealing with the cats though because a cat IS AN Animal, so anything you can do to/find out about the superclass animal you can certainly apply to a cat. I've tried casting the lotsOfCats ArrayList like so:
    ArrayList<Animal> myAnimals = (ArrayList<Animal>)lotsOfCats;But it didn't work. So is there any way for me to reference the ArrayList as type Animal without necessarily having to originally declare it that type? Or do I just have to suck it up and declare it type Animal from the get go?

    Thank you both for the responses. I gave you both helpful ratings because I think you both answered the question, just in different ways. fredrikl, your solution certainly works well. I'm sure I have seen that notation in documentation and such but haven't had experience using it yet. Your solution works out perfectly for my method since all I am trying to do is print out array components with it. I see you said you can't add components, that makes sense since the ArrayList doesn't really know what it is, but I figure you can still modify existing things in the list, right? Didn't actually try it yet but I have been using some casts to get out various things for display and that's working fine.
    morgalr, that's a complicated piece of code you have there. I don't fully understand it yet but I'll go through it again if I get this problem. From what I gather, it looks like you actually tried to solve my original problem and successfully did it?

  • Adding to an ArrayList

    I have been staring at this for 2 days now, and finally decided to ask the experts.
    I have a method of a class that should fetch records from a (textual) database en return an ArrayList with all the records. Each record in turn should contain all the (4) fields.
    Well, it pretty much all works fine, except for the fact that the line 'dbRecs.add(rec)' overwrites ALL ArrayList elements with the new record, instead of just the last. That is, I presume this is the case, since this is what a spying-loop showing the content af all the entries of the ArrayList (not included in the code, but added right after the wretched line) tells me.
    The code shows the method, and the class of the records with the fields.
    Any enlightenment on what the ... is wrong would be greatly appreciated.
    public ArrayList getDbRecords() {
              ArrayList dbRecs;
              String dbLine;
              String[] splitstring;
              dbRecs = new ArrayList(15);
              DbRecord rec;
              BufferedReader in;
              try {
                   FileInputStream fstream = new FileInputStream(SystemVars.dbFileName); // Open the file
                   in = new BufferedReader(new InputStreamReader(fstream));
                   rec = new DbRecord();
                   int i = 0;
                   while ((dbLine = in.readLine()) != null) { // Continue to read lines until eof
                        i++;
                        splitstring = dbLine.split("\"");
                        rec.proverb     = splitstring[1];
                        rec.nl = splitstring[3];
                        rec.transl = splitstring[5];
                        rec.extra = splitstring[7];
                        dbRecs.add(rec); //add record to ArrayList
                   } //end 'while'
                   in.close();
         catch (Exception e) {
                   System.err.println("File input error");
              dbRecs.trimToSize();
              return(dbRecs);
    class DbRecord {
         String proverb,nl,transl,extra;
    }

                   rec = new DbRecord();
                   int i = 0;
    while ((dbLine = in.readLine()) != null) { //
    // Continue to read lines until eof
                        i++;
                        splitstring = dbLine.split("\"");
                        rec.proverb     = splitstring[1];
                        rec.nl = splitstring[3];
                        rec.transl = splitstring[5];
                        rec.extra = splitstring[7];
    dbRecs.add(rec); //add
    /add record to ArrayList
    } //end
    end 'while'This is a real conceptual error. You are initialising the object outside the while loop and adding it to the list inside the loop. Everytime you reference the same object and the arraylist does nothing more than storing the references to them.
    The solution is to initialise the object each time in the loop, so that every object in the arraylist would refer to a different object.
    Another thing that I noticed is that the code is rather sloppy. You seem to have bypassed the concept of encapsulation totally... which defeats the very purpose of OOP. Make the member variables private and use getter/setter methods to access them.
    Phew!
    ***Annie***

  • Doubts in GeoRaster Concept.

    Hi everybody,
    I have few doubts in GeoRaster concepts.
    I did mosaicing of multiple Georasater objects using "sdo_geor.getRasterSubset()" and able to display image properly. But while doing this I come across few people suggestions. They said that mosaicing multiple rows together in a GeoRaster table is not going produce meaningful results because the interpolation methods wont have access to the data in the adjacent cells at the seams because cell needed exist in a different row (i.e. where two rows of GeoRaster either abut or overlap).
    I assume Oracle takes care of all this. Please suggest wheather my assumption is true or the statement given is true?
    Regards,
    Baskar
    Edited by: user_baski on May 16, 2010 10:49 PM

    Hi Jeffrey,
    Requirements:-
    I have to do mosaicing of 'n' number of Georaster objects. For eg, if table has 4 rows of GeoRaster object, then i have to create single image by mosaicing all the Georaster object based on the Envelope provided. (Note: I have to do this with Queries without using GeoRaster API)
    Workflow:-
    1. Get the connection and table details.
    2. Retrieve necessary information from the db like SRID, MAXPYRAMID, SPATIALRESOLUTION, EXTENT etc. For getting extent, I used SDO_AGGR_MBR function.
    3. With the help of "MDSYS.SDO_FILTER" and bouding box values, I create arraylist which contains raster id's retrieved from raster data table which covers the bouding box value provided in the filter command.
    4. Then I passed bounding box value into "sdo_geor.getCellCoordinate" function and I retrieved row and column number of Georaster image and created a number array which contains starting and ending row/column numbers.
    5. Then I had written a PL/SQL with "sdo_geor.getRasterSubset" function which takes the number array and raster id as input parameters, which inturn returns BLOB object.
    6. I am executing step 5 in a loop with all the raster id's that I got at step 3. For eg, arraylist size is 4, then I will have four BLOB object.
    7. Finally, I creating new image from the BLOB objects after some scaling and cropping based on the individual GeneralEnvelope of each raster id object.
    I had followed all the above steps and successfully created mosaic image.However, few people suggested that mosaicing in this way does not produce meaningful results because the interpolation methods wont have access to the data in the adjacent cells at the seams because cell needed exist in a different row. I assume Oracle will take care of these things. Moreover, they suggested to keep single row in GeoRaster table instead of muliple rows of Georaster object and suggested to use "SDO_GEOR.updateRaster" function to update a part of the raster object and the pyramids are rebuild automatically.
    So Please suggest which is the better way to do mosaicing. Wheather my assumption is correct or not?

  • JAXB Polymorphism of little use

    HI all.
    I am finding little use in JAXB's polymorphism. As such, I think I'm going to need to switch to another framework that has a more useful polymorphism feature (or else none at all).
    As indicated below, I have a schema that includes a "Person" complex type, and an "Employee" complex type that extends it. There is also an element "people" that is a sequence of "Person" elements. I have used JAXB-generated classes to add instances of Person and Employee (generated classes) to an instance of the People class. The marshaller then erroneously outputs the extensions to Person found in Employee (see below).
    Having seen this, I wonder what use polymorphism (in the classes generated by JAXB) has, if it is not acceptable to use a subclass wherever its superclass is allowed. Perhaps there is some other way to do polymorphism that I'm missing?
    I really want to have a functionality such as the code example below implies. Does JAXB have the feature I'm looking for, or do I need to switch to another framework? If I need to switch, which one should I use?
    Thanks for any help that can be offered.
    schema:
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
         <xs:element name="people">
              <xs:annotation>
                   <xs:documentation>Comment describing your root element</xs:documentation>
              </xs:annotation>
              <xs:complexType>
                   <xs:sequence>
                        <xs:element name="person" type="Person" maxOccurs="unbounded"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <xs:complexType name="Person">
              <xs:sequence>
                   <xs:element name="name" type="xs:string"/>
              </xs:sequence>
         </xs:complexType>
         <xs:complexType name="Employee">
              <xs:complexContent>
                   <xs:extension base="Person">
                        <xs:sequence>
                             <xs:element name="title" type="xs:string"/>
                        </xs:sequence>
                   </xs:extension>
              </xs:complexContent>
         </xs:complexType>
    </xs:schema>
    expected JAXB output:
    <people>
    <person>
    <name>Joe Sample</name>
    </person>
    <person>
    <name>Jane Sample Employee</name>
    </person>
    </people>
    actual JAXB output (invalid):
    <people>
    <person>
    <name>Joe Sample</name>
    </person>
    <person>
    <name>Jane Sample Employee</name>
    <title>Engineer</title>
    </person>
    </people>
    Java code:
    Person person = factory.createPerson();
    person.setName("Joe Sample");
    Employee employee = factory.createEmployee();
    employee.setName("Jane Sample Employee");
    employee.setTitle("Engineer");
    People people = factory.createPeople();
    people.getPerson().add(person);
    people.getPerson().add(employee);
    - Matt Munz

    hi Matt,
    I think your expected output may be wrong, and the actual output be correct eg consider this code:
    import java.util.*;
    class Person {
         String name;
         public String toString() { return "Person("+name+")"; } }
    class Employee extends Person {
         String title;
         public String toString() { return "Employee("+name+", "+title+")"; } }
    public class JBTest {
         public static void main(String[]arg) {
              List l = new ArrayList();
              Person p = new Person();
              p.name="Joe Sample";
              Employee q = new Employee();
              q.name="Jane Sample Employee";
              q.title="Engineer";
              l.add(p);
              l.add(q);
              System.out.println(l);
    which outputs
         [Person(Joe Sample), Employee(Jane Sample Employee, Engineer)]
    So although the List is untyped (am not keeping up with generics..
    sorry!) in the above code, even if it were a Person list it would still be legitimate to add an Employee to the list (since an Employee is-a
    Person)
    saying that, am not sure how you could achieve what you are trying? are you hoping for the object tree you construct not to be validated?
    thanks,
    asjf

  • Concept of object oriented programming

    does anyone have notes on concepts of object oriented programming language (Encapsulation,polymorphism,messages,class,inheritance and all that) i tried to find them but i only got definitions for them but i want advantages and disadvantages of concepts also plz can anyone help me

    You want the advantages/disadvantages.. hard to find... i got some notes on OO concepts.. u want? Please send me a email to [email protected].. will post it on geocities with the link once u send me the email

  • How to use Multimaps (Map String, ArrayList String )

    I was using an array to store player names, userIDs, uniqueIDs, and frag counts, but after reading about multimaps in the tutorials, it seems that would be much more efficient. However, I guess I don't quite understand it. Here's how I wanted things stored in my string array:
    String[] connectedUsers = {"user1_name", "user1_userid", "user1_uniqueid", "user1_frags"
                                            "user2_name"...}and here is how I'm attempting to setup and use the 'multimap':
    public class Main {
        static Map<String, ArrayList<String>> connectedUsers;
        public void updatePlayers(String name, String status) {
            String[] statusSplit = status.split(" ");
            if (connectedUsers.containsKey(name)) {
                connectedUsers.put(name, statusSplit[0]);
            else {
                connectedUsers.put(name, statusSplit[0]);
        }It's quite obvious I don't understand how this works, but should I even set this multimap up this way? Perhaps I should use a regular map with a string array for the values?

    You're cool MrOldie. Its just that alarm bells start ringing in my head when people come on and post as much as you do.
    * Created on Jul 28, 2005 by @author Tom Jacobs
    package tjacobs;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.LinkedList;
    import java.util.Map;
    import java.util.Set;
    import java.util.TreeSet;
    * ManyMap is a map that allows more than one value to be stored with any key
    * <p>
    * There are a number of methods in the class that have been deprecated because
    * the original functionality of Map has been violated to accomodate the concept
    * of the ManyMap
    public class ManyMap<T, T2> implements Map<T, T2> {
         private HashMap<T, ArrayList<T2>> mInnerMap;
         public ManyMap() {
              mInnerMap = new HashMap<T, ArrayList<T2>>();
          * @deprecated
         public T2 get(Object obj) {
              ArrayList<T2> ar = _get(obj);
              if (ar == null || ar.size() == 0) {
                   return null;
              return ar.get(0);
         public Iterator<T2> getAll(Object obj) {
              ArrayList<T2> ar = _get(obj);
              if (ar == null || ar.size() == 0) {
                   return null;
              return ar.iterator();          
         public T2 put(T obj1, T2 obj2) {
              ArrayList<T2> ar = _getNotNull(obj1);
              ar.add(obj2);
              return obj2;
         public Set<Map.Entry<T, T2>> entrySet() {
              TreeSet<Map.Entry<T, T2>> entries = new TreeSet<Map.Entry<T, T2>>();
              Iterator<T> _i = mInnerMap.keySet().iterator();
              while (_i.hasNext()) {
                   T key = _i.next();
                   Iterator<T2> vals = mInnerMap.get(key).iterator();
                   while (vals.hasNext()) {
                        Entry<T, T2> entry = new Entry<T, T2>(key, vals.next());
                        entries.add(entry);
              return entries;
         public int size() {
              return mInnerMap.size();
         public int valuesSize() {
              int vals = 0;
              Iterator<T> _i = mInnerMap.keySet().iterator();
              while (_i.hasNext()) {
                   T key = _i.next();
                   ArrayList<T2> ar = mInnerMap.get(key);
                   vals += ar.size();
              return vals;
         public void clear() {
              mInnerMap.clear();
         public void putAll(Map<? extends T, ? extends T2> map) {
              Iterator _i = map.entrySet().iterator();
              while(_i.hasNext()) {
                   Map.Entry<? extends T, ? extends T2> entry = (Map.Entry<? extends T, ? extends T2>) _i.next();
                   put(entry.getKey(), entry.getValue());
         public Collection <T2> values() {
              LinkedList ll = new LinkedList();
              Iterator<ArrayList<T2>> _i = mInnerMap.values().iterator();
              while (_i.hasNext()) {
                   ll.addAll(_i.next());
              return ll;
         public boolean containsValue(Object val) {
              Iterator<ArrayList<T2>> values = mInnerMap.values().iterator();
              while (values.hasNext()) {
                   if (values.next().contains(val)) return true;
              return false;
         public boolean containsKey(Object key) {
              return mInnerMap.containsKey(key);
         public T2 remove(Object obj) {
              Iterator<ArrayList<T2>> values = mInnerMap.values().iterator();
              boolean found = false;
              while (values.hasNext()) {
                   if (values.next().remove(obj)) {
                        found = true;
              return found ? (T2)obj : null;
         public boolean isEmpty() {
              return valuesSize() == 0;
         @SuppressWarnings("hiding")
         private class Entry<T, T2> implements Map.Entry<T, T2> {
              T key;
              T2 val;
              public Entry (T obj1, T2 obj2) {
                   key = obj1;
                   val = obj2;
              public T2 getValue() {
                   return val;
              public T getKey() {
                   return key;
              public T2 setValue(T2 obj) {
                   return val = obj;
         public Set<T> keySet() {
              return mInnerMap.keySet();
         public ArrayList<T2> _get (Object obj) {
              return mInnerMap.get(obj);
         public ArrayList<T2> _getNotNull (T obj) {
              ArrayList<T2> list = _get(obj);
              if (list == null) {
                   list = new ArrayList<T2>(1);
                   mInnerMap.put(obj, list);
              return list;
    }Edited by: tjacobs01 on Aug 19, 2008 12:28 PM

  • Help on polymorphism in my code

    Hi, I'd be glad if anyone could explain why java compiler gives errors
    compiling a class of a simple application.
    This is the scenario: class Point is meant to simplicistically abstract the
    concept of 2D point (x and y are the coordinates). Class Point3D extends Point,
    adding z coordinate. Attributes x, y and z are encapsulated (private and each
    one with setter and getter methods).
    There is a third class, called Ruler, its aim is to set the distance between
    two 2D points or two 3D points using the polymorphic method
    computeDistance(Point p1, Point p2).
    The compiler fails compiling the class Ruler with this message:
    Ruler.java:21: p1 is already defined in computeDistance(Point,Point)
    Point3D p1 = (Point3D) p1;
    ^
    Ruler.java:22: p2 is already defined in computeDistance(Point,Point)
    Point3D p2 = (Point3D) p2;
    ^
    2 errors
    This is the relevant part of the class:
    public class Ruler
        private double distance;
        public void computeDistance(Point p1, Point p2)
            if (p1 instanceof Point && p2 instanceof Point)
                // This is a 2D points case.
                // Obtain x1, x2, y1, y2 via getX() and getY() then  compute the
                // distance.
            else if (p1 instanceof Point3D && p2 instanceof Point3D)
                // This is a 3D points case.
                // Obtain x1, x2, y1, y2, z1, z2 using getX() and getY(), getZ().
                // BUT, in order to obtain z1, z2 it is needed a casting between
                // objects, because Point objects don't provide getZ(), while
                // Point3D do.
                Point3D p1 = (Point3D) p1;
                Point3D p2 = (Point3D) p2;
            else
                // This case is not valid.
    }If this piece of code is not enough I'll write in another post all the three
    classes exactly as they are.
    Thanks for any help!

    In Point, declare a computeDistance:
    public double computeDistance(Point other)
       // compute and return distance from this point to other point;
    }Override it in Point3D to account for the Z values:
    public double computeDistance(Point other)
       if (other instanceof Point3D)
          // Cast to Point3D
         // compute and return distance from this point to other point;
       else
           // decide how to handle (throw IllegalArgumentException, use Z=0, etc.)
    }Or, just try the cast, and allow the ClassCastException to fail [instead of explicitly throwing IllegalArgumentException]. Just document whatever it should do.
    In Ruler, do this, and it will do the polymorphism without instanceof:
    public void computeDistance(Point p1, Point p2)
       distance = p1.computeDistance(p2);
    }

Maybe you are looking for