2

I have a method which takes an Array of object as input and stores it in an instance variable. Here is the code that does it but, FindBugs reports it an error saying "May expose internal representation by incorporating reference to mutable object".

public final class HelloWorld
{
    public final Hello objs[];

    public HelloWorld(Hello[] inputs)
   {
        this.objs = inputs;
   }

}

I tried using Arrays.copyOf but, still i am getting this error.

this.objs = Arrays.copyOf(inputs,inputs.length);

How can i fix this FindBugs issue ?

yathirigan
  • 5,619
  • 22
  • 66
  • 104
  • as written, after someone constructs the Helloworld object, they can then change the contents of inputs (their variable) and it will change Helloworld's version. – MeBigFatGuy Dec 02 '15 at 04:26

1 Answers1

2

You should change your member to private :

private final Hello objs[];

While declaring the member as final prevents it from being assigned after first being initialized, it doesn't prevent its individual entries from being assigned by simply writing :

Hello[] harr = {new Hello(), new Hello()};
HelloWorld hw = new HelloWorld(harr);
hw.objs[1] = new Hello(); // this would mutate the contents of your array member
Eran
  • 387,369
  • 54
  • 702
  • 768
  • but how will a access modifier change fix this ? – yathirigan Nov 16 '15 at 16:47
  • @yathirigan You won't be able to access the array member from outside your class. (i.e. the 3rd line in my code snippet won't pass compilation) – Eran Nov 16 '15 at 16:49
  • got that but, after making it private, should i still be using Arrays.copyOf or just do a objs = inputs ? , i do have a getter method ( getObjs() ) for this instance variable. should i be using objs.clone() to return values in the getter method ? – yathirigan Nov 16 '15 at 16:57
  • 3
    @yathirigan You should still use `Arrays.copyOf`. Otherwise, in my example, you'll be able to mutate the member array by `harr[i]=...`. It might also be a good idea to return a copy of the array in your getter (assuming you don't won't the caller of that method to be able to mutate your member array). – Eran Nov 16 '15 at 17:00