Help again...

public void setCourses(int toSet [])
{
for (int i=0; i<toSet.length; i++)
courses[i]=toSet[i];
}

How do i do the getCourses?


Comments

  • : public void setCourses(int toSet [])
    : {
    : for (int i=0; i<toSet.length; i++)
    : courses[i]=toSet[i];
    : }
    :
    : How do i do the getCourses?
    :
    :
    :

    Note: System.arraycopy(..) is just a more efficient way of copying arrays than using a loop, but does essentially the same thing.

    [code]
    public class CourseKeeper {

    private int[] courses; //==null

    public void setCourses1(int[] c) {
    this.courses = c;
    }

    public int[] getCourses1() {
    return this.courses;
    }

    public void setCourses2(int[] c) {
    if (c == null) {
    this.courses = null;
    } else {
    this.courses = new int[c.length];
    System.arraycopy(c, 0, this.courses, 0, c.length);
    }
    }

    public int[] getCourses2() {
    if (this.courses == null) {
    return null;
    } else {
    int[] ret = new int[this.courses.length];
    System.arraycopy(this.courses, 0, ret, 0, this.courses.length);
    return ret;
    }
    }

    }
    [/code]

    There are two ways of doing this.

    Above, use case 2 if you want to make a copy of the array the class keeps immutable; i.e. other areas of the program cannot change the contents of the array without calling setCourses(int[]). If all you want is to keep a reference to an array, use case 1.

    ---------------------------------
    [size=1]HOWTO ask questions: http://catb.org/~esr/faqs/smart-questions.html[/size]

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion