0

Context (not strictly necessary to understand the question):

I have to implement a collection of elements. The class is called DocumentCollection. It is essentially an array of lists (a rudimentary form of a hash array), better formulated: an array of references to the first element of each respective list.

I already implemented a basic constructor, which takes an int as size of the array, and puts null initialized lists in each bucket.

One method to implement is removeAll. My first idea was to generate a new collection of the same size as the original one, and assign this to this newly created collection.

Below the code of the method.

    public boolean removeAll(){
        if(isEmpty()){
            return false;
        }
        int size = buckets.length;
        this = new DocumentCollection(size);
        return true;
    }

where buckets is the array.

As this is part of an assignment, I don't want to include the code of the whole class. This is enough for my question.

Intellij gives me the following error message (w.r.t. the line with this): variable expected.

Unfortunately this message is not eloquent enough for me to understand it.

Aside Note: yes, I could iterate over the array and assign null lists to them. That's not the point I am trying to make here

Question:

Am I doing something fundamentally wrong? In other words, is trying to give a new reference to the current object (i.e. this) illegal? Or can it be done, and I am simply using some wrong syntax?

LT_ichinen
  • 73
  • 4
  • 1
    It is illegal. Without seeing your class I'm not sure what you want to do precisely. – tgdavies Dec 03 '21 at 00:55
  • Even f the syntax was legal, the fact that [Java always passes objects by their reference-value (`stackoverflow.com`)](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) would render this "feature" useless or create a corner case, leading to very confusing semantics. – Turing85 Dec 03 '21 at 00:59

1 Answers1

1

You can't assign a new value to this since it is just a keyword to represent the current object along the class code, it is not a variable.

Beside's that, think of the semantics: you are inside the object asking it to become another object, that would be very tricky!

The closest you can get to that is to wrap some object as a field of your class, then you can assign a new instance to this field. Like this:

class MyObjectWrapper{
   private MyObject myObject = new MyObject();
   ...
   public void removeAll() {
       this.myObject = new MyObject();
   }
}

Check this related question: Why is assignment to 'this' not allowed in java?

Rafael Odon
  • 1,211
  • 14
  • 20