Swap two objects

Can anyone please explain to me why the following code does not swap two objects?
public void swap(Object a, Object b) {
Object temp = a;
a = b;
b = temp;
I know when you do a=b, it means assigning the b reference to a. So this piece of code should work. First assign the a reference to temp, then assign b referene to a and assign temp to b. So now a has b's reference and b has a's reference. So why is this wrong? Thanks.

Simply because all parameters are passed by
value, not by reference.right, to further clarify, all object parameters are references. So when you pass references by value, you make a copy of it and send it to the method. Therefore, changing what the reference points to has no effect outside of the method.

Similar Messages

  • Swap two objects method

    Hi,
    I got this code from the forum that can swap two objects. Can anyone explain the code to me? Thanks.
    public static Object swap(Object o1,Object o2){
    return o1;
    o2=swap(o1,o1=o2);
    It looks like o2=swap(o1,o1=o2) is passing o1 object and o2 object, the method create new reference for o1 and o2, return the o1 object and assign the reference to o2. Now o2 is o1 but how about o1?

    Don't touch that code, it's rubbish. The method claims to "swap" two objects, but it doesn't actually do that unless you call it in precisely that tricky and confusing way.
    Anyway, "swap two objects" is not a good way to ask the question because it confuses objects with the variables that refer to them. If you want to change two variables so that they each end up referring to the object originally referred to by the other, just write this:Object temp = o1;
    o1=o2;
    o2=temp;You can't do it with a method.

  • How swap two objects into a UILoader

    Hi.
    I'm taking a snapshot from a webcam and adding a frame around this snapshot.
    I add the snapshot before to load the frame from a file. How can I swap between those objects? because the frame appears at last and the snapshot appears infront. I wanna swap those in the way that the snapshot appears at last and then the frame.

    A UILoader (or any loader) can only hold/load one object, so I don't know how that fits into swapping two things into it.  If the frame is a movieclip, just use addChild(frameName) to have the frame move out front.

  • How to swap the position of two objects?

    I have four self made componensts that I imported them into my main mxml file
    and placed each on four corners.
    What I want to achieve is to drag each component onto others then swap their position.
    For example, comp A is dragged over comp B, when this is detected, swap the position of A and B.
    But at the moment it doesn't seem to work properly. I could not figure out what's wrong with my code. Could any one help me achieve that?
    Many thanks to any who could give me a hand!
    *********This is one of my component***********
    *********All other three components are made the same way, except each source of image file is different******************
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Box xmlns:mx="http://www.adobe.com/2006/mxml" width="42" height="42">
        <mx:Image source="Images/air.png"/>
    </mx:Box>
    *********This is my mxml that calls my components***********
    <?xml version="1.0" encoding="utf-8"?>
    <mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:comp="Comp.*" creationComplete = "onInit()">
        <mx:Script>
            <![CDATA[
                import mx.containers.Box;
                import Comp.Icon_illustrator;
                import Comp.Icon_air;
                import Comp.Icon_flash;
                import Comp.Icon_flex;
                private var i_1:Icon_air; //1
                private var i_2:Icon_flash; //2
                private var i_3:Icon_flex; //3
                private var i_4:Icon_illustrator; //4
                private var origX:Number;
                private var origY:Number;
                private var startObj:String;
                private var icons:Array;
                private var h_1:Box;
                private var h_2:Box;
                private var h_3:Box;
                private var h_4:Box;
                private function onInit():void{
                    //initialise all icons
                    i_1 = new Icon_air();
                    i_2 = new Icon_flash();
                    i_3 = new Icon_flex();
                    i_4 = new Icon_illustrator();
                    i_1.name = "i_1";
                    i_2.name = "i_2";
                    i_3.name = "i_3";
                    i_4.name = "i_4";
                    //populate icon
                    showArea.addChild(i_1);
                    showArea.addChild(i_2);
                    showArea.addChild(i_3);
                    showArea.addChild(i_4);
                    //set x position
                    i_1.x = 100;
                    i_2.x = 200;
                    i_3.x = 100;
                    i_4.x = 0;
                    //set y position
                    i_1.y = 0;
                    i_2.y = 100;
                    i_3.y = 200;
                    i_4.y = 100;
                    icons = [i_1, i_2, i_3, i_4];
                    //addEventListeners
                    for(var i:int=0; i<icons.length; i++){
                        icons[i].addEventListener(MouseEvent.MOUSE_DOWN, moveMe);
                        icons[i].addEventListener(MouseEvent.MOUSE_UP, stopDragMe);
                }//end of onInit
                private function moveMe(e:MouseEvent):void{
                    e.currentTarget.startDrag();   
                    showArea.setChildIndex(DisplayObject(e.currentTarget), 0);
                    origX = e.currentTarget.x;
                    origY = e.currentTarget.y;
                    startObj = e.currentTarget.name;   
                private function stopDragMe(e:MouseEvent):void{
                    if(this[startObj].hitTestObject(icons[1])){
                        trace("hit 2");
                        this[startObj].x = i_2.x;
                        this[startObj].y = i_2.y;
                        i_2.x = origX;
                        i_2.y = origY;
                    }else if(this[startObj].hitTestObject(icons[0])){
                        trace("hit 1");
                        this[startObj].x = i_1.x;
                        this[startObj].y = i_1.y;
                        i_1.x = origX;
                        i_1.y = origY;
                    }else{
                        trace("hit others");
                        this[startObj].x = origX;
                        this[startObj].y = origY;
                    e.currentTarget.stopDrag();
                }//end of stopDragMe
            ]]>
        </mx:Script>
        <mx:Panel id="showArea" width="400" height="300" layout="absolute" backgroundColor="0x999999"/>
    </mx:WindowedApplication>

    Here is a sample of swaping two objects in Flex (not Air)   I believe it is the same.  Take a look at the way the x and y coords are swapped using the dragInitator and the currentTarget object in the dragDropHandler.
    Hope this helps
    <?xml version="1.0" encoding="utf-8"?><mx:Application  xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:local="*">
     <mx:Script>
    <![CDATA[
     import mx.containers.Box; 
    import mx.core.UIComponent; 
    import mx.managers.DragManager; 
    import mx.core.DragSource; 
    import mx.events.DragEvent; 
    private var dragProxy:Box= new Box(); 
    public function dragDropHandler(e:DragEvent): void { 
    //These variables are the x and y coords of the objects 
    //the e.dragInitator is the object being dragged 
    //the e.currentTarget is the object being dropped on 
    //First save the x and y coords of each of the objects 
    var xdi:int = e.dragInitiator.x; 
    var ydi:int = e.dragInitiator.y; 
    var xct:int = e.currentTarget.x; 
    var yct:int = e.currentTarget.y; 
    //now switch them around.e.dragInitiator.x = xct;
    e.dragInitiator.y = yct;
    e.currentTarget.x = xdi;
    e.currentTarget.y = ydi;
    public function dragEnterHandler(event:DragEvent):void { 
    DragManager.acceptDragDrop(UIComponent(event.target));
    public function mouseMoveHandler(event:MouseEvent):void { 
    if(event.buttonDown == false) return; 
    var dragInitiator:UIComponent = event.target as UIComponent; 
    var dragSource:DragSource = new DragSource(); 
    dragProxy =
    new Box();dragProxy.width = dragInitiator.width;
    dragProxy.height = dragInitiator.height;
    dragProxy.setStyle(
    "borderStyle","solid")dragProxy.setStyle(
    "borderColor","0x000000")dragProxy.setStyle(
    "backgroundColor","0xc6c6c6"); 
    DragManager.doDrag(dragInitiator, dragSource, event, dragProxy,
    event.localX * -1, event.localY * -1, 1.00);
    ]]>
    </mx:Script>
     <mx:Canvas width="84" height="93" x="23" y="14" borderStyle="
    solid" borderColor="
    #030303" backgroundColor="
    #F83C3C"dragEnter="dragEnterHandler(event)"
    dragDrop="dragDropHandler(event)"
    mouseMove="mouseMoveHandler(event)"
    >
     </mx:Canvas>
     <mx:Canvas width="84" height="93" x="223" y="14" borderStyle="
    solid" borderColor="
    #030303" backgroundColor="
    #C5F83C"dragEnter="dragEnterHandler(event)"
    dragDrop="dragDropHandler(event)"
    mouseMove="mouseMoveHandler(event)"
    >
     </mx:Canvas>
     </mx:Application>

  • How to swap two primitive dataelements using swap function??

    How to write a swap function that can swap two integer..??

    Now we are getting somewhere. Next time you post code, use the code tags!! See Formatting Tips or just select the code and click the Code button.
    you cant swap i,j using the above code...You're right. You can't do that.
    so how to do that??The ints must be within some object, like I showed you
    You cannot swap the values of two arguments to a method and expect the caller's variables be swapped because Java passes arguments by value not reference. There is no such thing as a pointer to a variable in Java as there is in C/C++.

  • Additional data on relationship between two objects

    Hi
    We have a requirement to capture additional data on a relationship between two objects.  The data to be captured are custom fields that are unique to the relationship between the objects and not specific to either of the objects.
    We created a new object type and related it to the position (S)and the job (C) object.  In the customising (Personnel Management/Personnel Development/Basic Settings/Maintain Relationships there is an option to set up Additional Data.  There are however several restrictions (e.g. the substructure has to be in T77AD).  When you set up an existing substructure (e.g. PAD22) and screen (e.g. 3000), it works really well, however we have not been able to get this to read our own substructure and screen (since there is no customer include on HRP1001 and the 'Additional data' button seems to go to MP100100 to find the screen).
    My question is two fold:
    a) Is this an allowed customisation (e.g. can we create our own substructure, screen and Query string)? And if so, how does the data get into T77AD (since SAP recommends that data should not be added to this table)? and
    b) Is there any documentation on this (thus far I have only received info on how to enhance infotypes which I don't think is relevant???)?
    If this can not be maintained is there any other suggestions on how to deal with this scenario?
    Any assistance will be appreciated.
    Regards
    Liezl

    Hi everyone
    Thanks for everyone who tried to assist us with this.  I am happy to report that our in-house guru's have found the answer.  So, for anyone who is interested:
    In programme MP100100 you have a screen 6000 which is a customer enhancements screen.  We set up two in-house function modules for the PBO and PAI with its own screen and added an append structure to PAD31 to add the fields required.  In the configuration, we then specified PAD31 as the substructure with screen 6000 and then also specified our own PBO and PAI function modules.  The parameters required for screen 6000 is set up within our own customer screens.
    Hope this will be helpful to someone - it certainly seemed to open up some doors for us!
    Regards
    Liezl

  • Two objects created at the same time with the same hashcode

    We have this object with the following constructor:
    2010-06-24 00:10:31,260 [LoadBalancerClientSubscriber(3)(pid:24312)] INFO  com.intel.swiss.sws.netstar.application.caching.framework.data
    set.synchronizer.DatasetSynchronizer - Initializing dataset synchronizer for: [/nfs/iil/iec/sws/work/damar/ds_cama/tmp/ds_126631277304794
    /d81], i am com.intel.swiss.sws.netstar.application.caching.framework.dataset.synchronizer.DatasetSynchronizer@2ed3cae0
    2010-06-24 00:10:31,260 [LoadBalancerClientSubscriber(5)(pid:24315)] INFO  com.intel.swiss.sws.netstar.application.caching.framework.data
    set.synchronizer.DatasetSynchronizer - Initializing dataset synchronizer for: [/nfs/iil/iec/sws/work/damar/ds_cama/tmp/ds_126631277304794
    /d31], i am com.intel.swiss.sws.netstar.application.caching.framework.dataset.synchronizer.DatasetSynchronizer@2ed3cae0Note that two objects are created by different threads with exactly the same hash code. Any idea if/how this is possible?

    isocdev_mb wrote:
    The last part definitely suggests already that relying on uniqueness is incorrect. Hash codes are very often equal on distinct objects, viz. new String("java").hashCode == new String("java").hashCode(). Use a class level counter as suggested earlier.For that case we would of course expect the hashCodes to be equal, since the objects are equal. But even in the case of non-equal objects that don't override hashCode, you can still get the same value. Or, for that matter, non-equal objects that do override it. There are 2^32 possible hashCode values. There are 2^64 possible Long values. That means that there are 2^32 Longs that have a hashCode of 1, 2^32 Longs that have a hashCode of 2, etc.
    And for non-equal objects...
    package scratch;
    import java.util.Set;
    import java.util.Map;
    import java.util.HashMap;
    public class HashCodeIsNotUnique {
      public static void main(String[] args) throws Exception {
        Map<Integer, Integer> hashCodeCounts = new HashMap<Integer, Integer>();
        int numObjects = 10000;
        for (int i = 0; i < numObjects; i++) {
          Object obj = new Object();
          int hashCode = obj.hashCode();
          if (!hashCodeCounts.containsKey(hashCode)) {
            hashCodeCounts.put(hashCode, 0);
          hashCodeCounts.put(hashCode, hashCodeCounts.get(hashCode) + 1);
        for (Map.Entry<Integer, Integer> entry : hashCodeCounts.entrySet()) {
          int key = entry.getKey();
          int value = entry.getValue();
          if (value > 1) {
            System.out.println(key + " occurred " + value + " times");
    9578500 occurred 2 times
    14850080 occurred 2 times

  • How to add two objects on scene and how to rotate them?

    I am beginer on 3d. I am trying do write applet where are 3x3x3 rubic.
    My plans are to have 27 litle cubes. There are 6 flats (9 cubes in a flat) so i have six objects groups. My problem at this moment is that i cant find out how to make two objets. Each of this two objects consists from couple more litle objects. Some of litle objects can be in first and second big object. For example it can be two flats of rubic (corner).
    Is anybody have some examples or somehow to hepl me to find out.
    Thanks a lot

    I have code :
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import com.sun.j3d.utils.applet.MainFrame;
    import com.sun.j3d.utils.behaviors.mouse.*;
    import com.sun.j3d.utils.universe.SimpleUniverse;
    import javax.media.j3d.*;
    import javax.vecmath.AxisAngle4f;
    import javax.vecmath.Color3f;
    import javax.vecmath.Vector3f;
    public class RubicApplet extends Applet implements MouseListener
         TransformGroup objRotate = null;
    public BranchGroup createSceneGraph(SimpleUniverse su,Canvas3D canvas)
         // Create the root of the branch graph
         BranchGroup objRoot = new BranchGroup();
         objRoot.setCapability(BranchGroup.ALLOW_DETACH);
    Transform3D transform = new Transform3D();
         transform.setRotation(new AxisAngle4f(.5f,1f,1f,.5f));
    BoundingSphere behaveBounds = new BoundingSphere();
    // create Cube and RotateBehavior objects
    objRotate = new TransformGroup(transform);
    objRotate.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
    objRotate.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
    objRotate.setCapability(TransformGroup.ENABLE_PICK_REPORTING);
    // Colors
    Color3f gray = new Color3f(0.2f,0.2f,0.2f);
    Color3f red = new Color3f(1.0f,0.0f,0.0f);
    Color3f white = new Color3f(1.0f,1.0f,1.0f);
    Color3f yellow = new Color3f(1.0f,1.0f,0.0f);
    Color3f green = new Color3f(0.0f,1.0f,0.0f);
    Color3f blue = new Color3f(0.0f,0.0f,1.0f);
    Color3f purple = new Color3f(1.0f,0.0f,1.0f);
         // Object possition
    float x=-0.5f;
    float y=-0.5f;
    float z=-0.5f;
    objRoot.addChild(objRotate);
         // colors for: back, front, right, left, bottom, top
    Color3f[] myColors0 = {white,gray,gray,red,blue,gray};
    RCube cube1 = new RCube(myColors0,new Vector3f(x-1,y-1,z-1));
         // colors for: back, front, right, left, bottom, top
    Color3f[] myColors1 = {gray,gray,gray,red,blue,gray};
         RCube cube2 = new RCube(myColors1,new Vector3f(x-1,y-1,z+1));
         // colors for: back, front, right, left, bottom, top
    Color3f[] myColors2 = {gray,yellow,gray,red,blue,gray};
         RCube cube3 = new RCube(myColors2,new Vector3f(x-1,y-1,z+3));
    // colors for: back, front, right, left, bottom, top
    Color3f[] myColors3 = {white,gray,gray,red,gray,gray};
         RCube cube4 = new RCube(myColors3,new Vector3f(x-1,y+1,z-1));
    objRotate.addChild(cube1);
    objRotate.addChild(cube2);
    objRotate.addChild(cube3);
    objRotate.addChild(cube4);
    MouseRotate myMouseRotate = new MouseRotate();
    myMouseRotate.setTransformGroup(objRotate);
    myMouseRotate.setSchedulingBounds(new BoundingSphere());
    objRoot.addChild(myMouseRotate);
    MouseTranslate myMouseTranslate = new MouseTranslate();
    myMouseTranslate.setTransformGroup(objRotate);
    myMouseTranslate.setSchedulingBounds(new BoundingSphere());
    objRoot.addChild(myMouseTranslate);
    MouseZoom myMouseZoom = new MouseZoom();
    myMouseZoom.setTransformGroup(objRotate);
    myMouseZoom.setSchedulingBounds(new BoundingSphere());
    objRoot.addChild(myMouseZoom);
    // Let Java 3D perform optimizations on this scene graph.
    objRoot.compile();
         return objRoot;
    public RubicApplet()
    setLayout(new BorderLayout());
    GraphicsConfiguration config =SimpleUniverse.getPreferredConfiguration();
    Canvas3D canvas3D = new Canvas3D(config);
    canvas3D.addMouseListener(this);
    add("Center", canvas3D);
    SimpleUniverse simpleU = new SimpleUniverse(canvas3D);
    BranchGroup scene = createSceneGraph(simpleU,canvas3D);
         simpleU.getViewingPlatform().setNominalViewingTransform();
    simpleU.addBranchGraph(scene);
    public static void main(String[] args)
    Frame frame = new MainFrame(new RubicApplet(), 600, 600);
         public void mouseClicked(MouseEvent e)
         public void mouseEntered(MouseEvent e)
         public void mouseExited(MouseEvent e)
         public void mousePressed(MouseEvent e)
         public void mouseReleased(MouseEvent e)
    I need to rotate with some event two cubes and with some other event rotate three cubes

  • Two objects claim ownership of UID: U15536 Class: TextFrame

    I have a problem : When I try to save a project of Muse or attempt to modify it, the error " : U15536 Class: Two objects claim ownership of UID. TextFrame "
    I have installed the version 2014.2 CC Muse
    How I can fix it?
    Thankyou.

    My sincere apologies for the disconnect. I searched the [email protected] case system and found no messages from your e-mail address. Perhaps the file was sent using a file sharing service or from a different e-mail address? We sometimes receive files from sharing services that provide no return e-mail address and that have no other information to connect the sharing invite with a forum thread or customer, so we're left with no way to reconnect with the customer.
    I'm personally far less active on the forums since the first of the year. My primary role on Muse has always been as a Developer. I've historically spent a lot of my own time and too much of my work time here on the forum, versus directly working on developing Muse. Since the first of the year, I'm redirecting my time to development. I'm no longer reading every message or checking forum traffic on a regular basis, so I didn't see you last two messages until now.
    If you send your current .muse file to [email protected], I'll see that it gets repaired and returned in a timely fashion. If you send a second message with no attachment directly to me, [email protected], I'll confirm the message to [email protected] was received.
    We very recently had a break through and determined the pattern of activity that can lead to this damage within a file. We have a fix currently in testing that will be included in the next release (in a few weeks).

  • Two objects claim ownership of UID: U3615 Class: Text Frame

    Hi guys,
    since i updated today i can't save my project file anymore. Getting an error when i try to save saying:
    Two objects claim ownership of UID: U3615 Class: Text Frame
    Is there a way to fix it or did i lose all my progress from today? That would be devastating.
    Greetings,
    Joern

    Please send us a copy of your .muse file at [email protected] and include a link to this thread. If it's too big for e-mail (>20 mb) you could use a service like Dropbox, Adobe SendNow, WeTransfer, etc. We'll repair and return.

  • Two objects moving around with mouse

    I'm making a catching game and I only wanted the falling objects hit certain area on my catcher. My catcher is a girl with mouth open and I wanted the falling objects to hit only the mouth, not any other parts of her body like arms. So I made two objects, the full girl and just the mouth. How do I make the two objects (movieclips) move around with the mouse?
    I tried to embed one object into another but it didn't work....
    This is actionscript I wrote so far:
    package {
        import flash.display.*;
        import flash.events.*;
        import flash.text.*;
        import flash.utils.Timer;
        import flash.utils.getDefinitionByName;
        public class CatchingSkittles extends MovieClip {
            var girlmouthfront:GirlMouthFront;
            var girlmouth:GirlMouth;
            var nextObject:Timer;
            var objects:Array = new Array();
            var score:int = 0;
            const speed:Number = 7.0;
            public function CatchingSkittles() {
                girlmouthfront = new GirlMouthFront();
                girlmouthfront.y = 258.00;
                addChild(girlmouthfront);
                setNextObject();
                addEventListener(Event.ENTER_FRAME, moveObjects);
            public function setNextObject() {
                nextObject = new Timer(1000+Math.random()*1000,1);
                nextObject.addEventListener(TimerEvent.TIMER_COMPLETE,newObject);
                nextObject.start();
            public function newObject(e:Event) {
                var goodObjects:Array = ["Red","Purple","Yellow","Orange","Green"];
                if (Math.random() < .5) {
                    var r:int = Math.floor(Math.random()*goodObjects.length);
                    var classRef:Class = getDefinitionByName(goodObjects[r]) as Class;
                    var newObject:MovieClip = new classRef();
                    newObject.typestr = "good";
                } else {
                    r = Math.floor(Math.random()*goodObjects.length);
                    classRef = getDefinitionByName(goodObjects[r]) as Class;
                    newObject = new classRef();
                    newObject.typestr = "good";
                newObject.x = Math.random()*500;
                addChild(newObject);
                objects.push(newObject);
                setNextObject();
            public function moveObjects(e:Event) {
                for(var i:int=objects.length-1;i>=0;i--) {
                    objects[i].y += speed;
                    if (objects[i].y > 425) {
                        removeChild(objects[i]);
                        objects.splice(i,1);
                    if (objects[i].hitTestObject(girlmouthfront)) {
                        if (objects[i].typestr == "good") {
                            score += 5;
                        } else {
                            score += 5;
                        if (score < 0) score = 0;
                        scoreDisplay.text = "Score: "+score;
                        removeChild(objects[i]);
                        objects.splice(i,1);
                girlmouthfront.x = mouseX;

    Never mind. I got everything to work. Thanks for your help! I changed my code to:
    [code]
    public class CatchingSkittles extends MovieClip {
            var girlmouth:GirlMouth;
            var girlmouthfront:GirlMouthFront;
            var nextObject:Timer;
            var objects:Array = new Array();
            var score:int = 0;
            const speed:Number = 7.0;
            public function CatchingSkittles() {
                girlmouthfront = new GirlMouthFront();
                girlmouthfront.y = -49.00;
                girlmouth = new GirlMouth();
                girlmouth.y = 308.55;
                addChild(girlmouth);
                girlmouth.addChild(girlmouthfront);
                setNextObject();
                addEventListener(Event.ENTER_FRAME, moveObjects);
    [/code]

  • How to swap two numbers in java

    i have an idea in c but i don't know in java..somenoe like to share their idea i appreciate a lot...
    here is a sample code in c...hope u can help me in java.....thanks a lot ....
    #include<stdio.h>
    void swap(int x, int y)
    int temp;
    temp=x;
    x=y;
    y=temp;
      void main(void)
        int x=10,y=20;
          clrscr();
    printf("Before swap:x=%d,y-%d", x,y);
        swap(x,y);
    printf("\n After swap:x=%d,y=%d",x,y);
       getch();
    #include<stdio.h>
    void swap(int* x, int* y)
    int temp;
    temp=*x;
    *x=*y;
    *y=temp;
    void main(void)
    int x=10,y=20;
    clrscr();
    printf("Before swap:x=%d,y-%d", x,y);
    swap(&x,&y);
    printf("\n After swap:x=%d,y=%d",x,y);
    getch();
    }My aim of this program is to make one java file and 2 class files in java and display the output . The first output would be the number before swapping and the number after swapping.....

    There are several ways to achieve the results. You can use an array or a custom "Swaper" class to swap two values. Here is an example using generics for better code reuse.
    public class Swapper<T> {
       private T first;
       private T second;
       public Swapper(T first, T second) {
          this.first = first;
          this.second = second;
       public void swap() {
          T temp = first;
          first = second;
          second = temp;
       public <T> Swapper<T> swap(T first, T second) {
          return new Swapper<T>(second, first);
       public T getFirst() {return first;}
       public T getSecond() {return second;}
       private static void swap(int[] num) {
          if (num.length != 2) {
             throw new IllegalArgumentException("num array must be of length 2");
          int temp = num[0];
          num[0] = num[1];
          num[1] = temp;
       public static void main(String[] args) {
          // method 1: use array
          int[] num = {1, 2};
          System.out.printf("Before swap:first=%d,second=%d\n", num[0], num[1]);
          Swapper.swap(num);
          System.out.printf("After swap:first=%d,second=%d\n", num[0], num[1]);
          // method 2: use a custom "Swapper" class
          Swapper<Integer> swapper = new Swapper<Integer>(3, 4);
          System.out.printf("Before swap:first=%d,second=%d\n", swapper.getFirst(), swapper.getSecond());
          swapper.swap();
          System.out.printf("After swap:first=%d,second=%d\n", swapper.getFirst(), swapper.getSecond());
          // method 2: using another data type
          Swapper<String> stringSwapper = new Swapper<String>("C#", "Java");
          System.out.printf("Before swap:first=%s,second=%s\n", stringSwapper.getFirst(), stringSwapper.getSecond());
          stringSwapper.swap();
          System.out.printf("After swap:first=%s,second=%s\n", stringSwapper.getFirst(), stringSwapper.getSecond());
          /*    --- OUTPUT ---
           * Before swap:first=1,second=2
           * After swap:first=2,second=1
           * Before swap:first=3,second=4
           * After swap:first=4,second=3
           * Before swap:first=C#,second=Java
           * After swap:first=Java,second=C#
    }

  • Two objects from one table

    My current setup is two tables and two objects with a one to one relationship between them, Object and ObjectMD (metadata).
    Not sure why my predecessors set it up like this but...that's how it is.
    The problem is that my Object table (and thus ObjectMD also) has reached 40 million rows and large joins between Object and ObjectMD are taking forever and are completely unnecessary.
    I want to import the ObjectMD data into the Object table and go forward with a single table. The problem is that the ObjectMD table has it's own java surrounding it and that code is used in way too many places to weed it out. I need to leave the Java object structure in place.
    I think I should be able to create both these objects from a single table, but I can not figure out the descriptor. My set method needs to be getMetaData().setMethod, but of course TL's reflection doesn't like this. I suppose I could create new methods in Object to get/set all these fields and just forward them to the real methods.
    How can I define descriptors to create two objects from a single table?

    What I decided on for my last problem was to use a method to setBar, and inside that method, set the Foo of the Bar.
    Here are my files for future reference:
    --------------------------------------Foo.java-------------------------------------
    public class Foo {
         public int id;
         public String first;
         public Bar bar;
         public void setBar(Bar newBar){
              if(newBar != null){
                   newBar.foo = this;
              this.bar = newBar;
    --------------------------------------Bar.java-------------------------------------
    public class Bar {
         public Foo foo;
         public String second;
    --------------------------------------Descriptors.java-------------------------------------
    public class Descriptors {
         public static void addDescriptors(Project project) {
    project.addDescriptor(Descriptors.buildFooDescriptor());
    project.addDescriptor(Descriptors.buildBarDescriptor());
    private static Descriptor buildFooDescriptor() {
    Descriptor descriptor = new Descriptor();
    //     basic information
    descriptor.setJavaClass(Foo.class);
    descriptor.addTableName("FOO");
    descriptor.setPrimaryKeyFieldName("ID");
    //     mappings
    DirectToFieldMapping directToFieldMapping;
    AggregateObjectMapping aggregateObjectMapping;
    //     id mapping
    directToFieldMapping = new DirectToFieldMapping();
    directToFieldMapping.setAttributeName("id");
    directToFieldMapping.setFieldName("ID");
    descriptor.addMapping(directToFieldMapping);
    //     first mapping
    directToFieldMapping = new DirectToFieldMapping();
    directToFieldMapping.setAttributeName("first");
    directToFieldMapping.setFieldName("FIRST");
    descriptor.addMapping(directToFieldMapping);
    //     bar mapping
    aggregateObjectMapping = new AggregateObjectMapping();
    aggregateObjectMapping.setAttributeName("bar");
    aggregateObjectMapping.setReferenceClass(Bar.class);
    aggregateObjectMapping.setSetMethodName("setBar");
    aggregateObjectMapping.dontAllowNull();
    descriptor.addMapping(aggregateObjectMapping);
    return descriptor;
    private static Descriptor buildBarDescriptor() {
    Descriptor descriptor = new Descriptor();
    // basic information
    descriptor.descriptorIsAggregate();
    descriptor.setJavaClass(Bar.class);
    //     mappings
    DirectToFieldMapping directToFieldMapping;
    //     second mapping
    directToFieldMapping = new DirectToFieldMapping();
    directToFieldMapping.setAttributeName("second");
    directToFieldMapping.setFieldName("SECOND");
    descriptor.addMapping(directToFieldMapping);
    return descriptor;
    ----------------------------------------Go.java------------------------------------
    public class Go {
         public static void main(String[] args) {
              if(args.length != 0){
                   throw new RuntimeException("Arguments are not supported");
              Project project = new Project();
              project.setName("fooBarProject");
              DatabaseLogin login = new DatabaseLogin();
         login.usePlatform(new Oracle9Platform());
         login.setDriverClassName("oracle.jdbc.driver.OracleDriver");
         login.setConnectionString("jdbc:oracle:thin:@nnn.nnn.nnn.nnn:nnnn:SERVICE");
         project.setDatasourceLogin(login);
         Descriptors.addDescriptors(project);
         Server server = project.createServerSession(2, 2);
         server.setLogLevel(oracle.toplink.sessions.SessionLog.FINE);
         server.login("schema", "password");
         Session session = server.acquireClientSession();
         UnitOfWork uow = session.acquireUnitOfWork();
         Foo fooBar = (Foo) uow.newInstance(Foo.class);
         fooBar.id = (int) (Math.random() * 10000);
         fooBar.first = "abcd";
         uow.commit();
         ExpressionBuilder builder = new ExpressionBuilder();
         Foo fooBarLoad = (Foo) session.readObject(Foo.class, builder.get("id").equal(fooBar.id));
         System.out.println("ID:" + fooBarLoad.id + " FIRST:" + fooBarLoad.first + " SECOND:" + fooBarLoad.bar.second );
         session.release();
         server.logout();
    ------------------------------------------------------------------------------------------

  • Can I combine two objects into one?

    Hi all:
    I got a problem here: I just wonder if anyone knows how to combine the informations which I grabed from a SQL database to an object I obtained from an OO database at runtime.
    I look forward to your reply and appreciate your concern!
    regards
    David
    at [email protected]

    Thanks for you reply, but the combined two objects can not be pre-defined because it is defined at runtime, say, there are a number of objects in database, only when you select the one for combining, you know what it is!
    Cheers
    David

  • More space between two objects (using twitter bootstrap 3)

    I have two specific objects on my website and they are to close together. I would like to know if there is a way to push the a bit farther apart from eachother. They are in the same row. I was told to increase container width but i am not sure how to do this. The two objects are the image slider and the picture. Also, how would i push that row down. It's to close to the navbar.
    My code:
    <div class="container">
            <div class="row">
                    <div class="col-xs-9">
                            <ul class="bxslider">
                                    <li><img src="img/Day1.jpg" width="980" height="280"/></li>
      <li><img src="img/Day1.jpg" width="980" height="280"/></li>
      <li><img src="img/Day1.jpg" width="980" height="280"/></li>
      <li><img src="img/Day1.jpg" width="980" height="280"/></li>
                            </ul>
                    </div>
                    <div class="col-xs-3">
                            <div class="imagess"> <img src="http://rootforsite.azurewebsites.net/img/pic.jpg" class="img-responsive center-block"  /> </div>
                    </div>
            </div>
      <iframe width="640" height="360" src="http://www.youtube.com/embed/mb6SNytt5YI" frameborder="0" allowfullscreen></iframe>
    </div>
    My Website : http://rootforsite.azurewebsites.net/
    -Thanks

    Please do not duplicate your posts. It can be very confusing when two different persons answer the post in different ways.

Maybe you are looking for

  • BN transactions in Cash Flow report

    Hi, in SBO 2007, while proceeding to bank reconciliation, one may add adjustment entries if needed. These transactions are coded as BN instead of JE. The question is why aren't those transactions displayed in the Cash Flow report ? Thanks Gilles Plan

  • Help Installing an older version of iTunes

    I recently installed iOS 7 on my iPhone 4s and -- because I was running iTunes 10.6 -- was required to install iTunes 11.1 With iTunes 11.1, I can't access the iTunes Store.  Whenever I try, the progress bar gets almost to the end and then iTunes cra

  • Query to get details from Maintenance plans

    Hi All, Could some one please let me know, if there is any way to check whether all  databases option is selected under the maintenance plan other than using GUI. Below is the print screen for reference. Maintenance plan includes rebuild Index, check

  • 3D Hardware accelaration

    The video card a ATI Radeon 9800 PRO in my mac MDD 2x1,25 GHz, 2GB RAM (System 10.4.11) is not detected for hardware accelaration. Do i need a special driver or is the card to old for... Thank you for comments.

  • Hypervinculo a pdf

    Me gustaria hacer que a traves de un hyperlink pudiera abrir un archivo pdf. He conseguido abrir un archivo con un ejemplo que me he bajado (archivo adjunto) pero no se si es lo mas correcto o si es una solucion, que aunque valida, antigua. Gracias A