Results 1 to 3 of 3
  1. #1
    pj6444 is offline Senior Member
    Join Date
    Jan 2013
    Posts
    165
    Rep Power
    2

    Default Objects Being Passed As Parameters

    Hi all,

    I have a quick question for you guys.

    If I have a method that takes an ArrayList of a class called Piece and it uses the setPosition() method from Piece. It is changing the value of the array that I passed in, but I want the ArrayList to stay the same outside of the method. Is there any way I can change only the values on the inside of the method, but keep the same position values outside the method?

    Thank you all.

    Here is an example.


    Piece class
    Java Code:
    public class Piece {
        private int xCoor;
        private int yCoor;
    
        public Piece(int xCoor, int yCoor) {
            this.xCoor = xCoor;
            this.yCoor = yCoor;
        }
    
        public void setPosition(int xCoor, int yCoor) {
            this.xCoor = xCoor;
            this.yCoor = yCoor;
        }
    }
    Java Code:
    public static void main(String[] args) {
        ArrayList<Piece> pieces = new ArrayList<Piece>();
        for(int i = 0; i < 10; i++) {
            pieces.add(new Piece(8, 8));
        }
    
        
        changePos(pieces);
    }
    
    public static void changePos(ArrayList<Piece> pieces) {
        for(int i = 0; i < pieces.size(); i++) {
            pieces.get(i).setPosition(10, 10);
        }
    }

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,785
    Rep Power
    5

    Default Re: Objects Being Passed As Parameters

    You need to pass in a copy of the array list which contains copies of each of the Piece class. Passing in
    a simple copy of the array list won't work as both the original and copied list still contain the same
    references to Piece.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  3. #3
    pj6444 is offline Senior Member
    Join Date
    Jan 2013
    Posts
    165
    Rep Power
    2

    Default Re: Objects Being Passed As Parameters

    That makes sense. Thank you very much.

Similar Threads

  1. Replies: 2
    Last Post: 05-07-2013, 03:51 AM
  2. Replies: 12
    Last Post: 04-29-2012, 02:55 PM
  3. Replies: 1
    Last Post: 02-10-2012, 09:17 PM
  4. URL parameters not getting passed during javascript submit
    By fierof2 in forum JavaServer Pages (JSP) and JSTL
    Replies: 2
    Last Post: 10-01-2011, 08:26 AM
  5. hiding passed parameters using window.location.href = 'params' method
    By kulangotski in forum JavaServer Pages (JSP) and JSTL
    Replies: 0
    Last Post: 07-01-2011, 12:49 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •