I have a question about using getter methods in java.
Suppose I had this class:
class Test {
private ArrayList<String> array = new ArrayList<String>();
public ArrayList getArray() {
return this.array;
}
public void initArray() {
array.add("Test 1");
array.add("Test 2");
}
}
class Start {
public static void main(String args[]) {
initArray();
getArray().remove(0);
}
}
My question is:
Would the actual arraylist object be modified ("Test 1" removed from it)? I think I have seen this in places, but I thought that getters were simply providing a copy of that object. Not a reference to it. If it did work that way (as a reference), then would this work as well (Would the arraylist object of the class Test be altered by this as well)?:
class Start {
public static void main(String args[]) {
initArray();
ArrayList aVar = getArray();
aVar.remove(0);
}
}
Java returns references to the Array, so it won't be a copy and it will modify the List. In general, unless its a primitive type (int,float,etc) you will be getting a reference to the object.
You have to explicitly copy the array yourself if you want a duplicate to be returned.
The way I understand it, Object reference variables are little more than memory addresses of the objects themselves. So what is returned from getArray() is a reference variable to that ArrayList. An object may have many reference variables, but it is still the same object that gets modified.
Java does everything pass by value. So anytime you pass an object reference variable as a parameter or return it's value, you are passing or returning the value of the object reference variable.
As others said, unless it's a primitive type, you get a reference to the object. It is similar to a pointer in C++, it allows you to access the object, but unlike C++ reference (pointer to the memory address of a variable) it doesn't allow you to replace it with another object. Only setter can do that.
I see two variants in your question, test.getArray().remove(0) and aVar.remove(0). There is no difference in the results of those, it's still just some pointer-like reference and it modifies the original.
You never get a clone by just calling a getter, so unless the object is immutable, you can modify the object that the getter gave you access to. For example, String is immutable, any basic Collection (including ArrayList) is mutable. You can call Collections.unmodifiable*(...) to make a collection unmodifiable. However, if the items of collection are mutable, they can still be changed.
In some cases, getting a clone is a good idea, in most cases it's not. A getter shouldn't clone anything at all, it shouldn't even modify data unless it initializes a possibly null collection or something like that. If you want an unmodifiable collection containing immutable objects, try to do it this way. In this example we have a class FooImpl that implements interface Foo, the reasons to be explained later.
public interface Foo {
int getBar();
}
public class FooImpl Foo {
private int bar;
#Override
public int getBar() {
return bar;
}
public void setBar(int newValue) {
this.bar = newValue;
}
}
As you see, Foo has no setter. If you create some ArrayList<Foo> and pass it from some getter as Collections.unmodifiableList(myArrayList), it almost seems you did it. But the work is not done yet. If the class FooImpl is public (which it is in this case), someone might try if that foo he found in the list is an instanceof FooImpl and then cast it as (FooImpl) foo making it mutable. However, we can wrap any Foo into a wrapper called FooWrapper. It implements Foo as well:
public class FooWrapper implements Foo {
private Foo foo;
public FooWrapper(Foo foo) {
this.foo = foo;
}
public int getBar() {
return foo.getBar();
}
// No setter included.
}
Then we can put a new FooWrapper(myFoo) into a Collection<FooWrapper>. This wrapper doesn't have any public setter and the foo inside is private. You cannot modify the underlying data. Now about that Foo interface. Both FooImpl and FooWrapper implement it, if any method doesn't intend to modify the data, it can ask for Foo on input. It doesn't matter which Foo you get.
So, if you want unmodifiable collection containing unmodifiable data, make a new Collection<Foo>, feed it with FooWrapper objects and then call Collections.unmodifiable*(theCollection). Or make a custom collection that wraps the whole collection of Foo, returning FooWrappers, for example this list:
public MyUnmodifiableArrayList implements List<Foo> {
ArrayList<Foo> innerList;
public get(int index) {
Foo result = innerList.get(index);
if (!(result instanceof FooWrapper)) {
return new FooWrapper(result);
}
return result; // already wrapped
}
// ... some more List interface's methods to be implemented
}
With wrapped collection, you don't have to iterate through the original collection and make its clone with wrappers of data. This solution is much better when you don't read it whole, but it creates a new FooWrapper every time you call get() on it, unless the Foo on that index is already a FooWrapper. In a long running thread with millions of calls to get(), this could become an unnecessary benchmark for the garbage collector, making you use some inner array or map containing already existing FooWrappers.
Now you can return the new, custom List<Foo>. But again, not from a plain getter. Make it something like getUnmodifiableFooList() for your private ArrayList<FooImpl> fooList field.
As pointed out, your getter does not modify the list, it returns an modifiable reference to the list. Tools like Findbugs will warn you about that... you may either live with that and trust the users of your class to not clobber your list, or use this to return an unmodifiable reference to your list:
public static List<String> getArray() {
return Collections.unmodifiableList(array);
}
To answer your question, with a getter you get direct access to a variable.
Run this code and you can see that the String in the ArrayList is removed. But don't use a static ArraList like in this example in your code.
public class Test {
private static ArrayList<String> array = new ArrayList<String>();
public static ArrayList<String> getArray() {
return array;
}
public static void initArray() {
array.add("Test 1");
array.add("Test 2");
}
public static void main(String[] args) {
initArray();
ArrayList aVar = getArray();
aVar.remove(0);
System.out.println(aVar.size());
}
}
That a getter does not modify the object you call it upon is purely a matter of convention. It certainly does not change the target's identity, but it can change its internal state. Here's a useful example, if a bit sketchy:
public class Fibonacci {
private static ConcurrentMap<Integer, BigInteger> cache =
new ConcurrentHashMap<>();
public BigInteger fibonacci(int i) {
if (cache.containsKey(i)) {
return cache.get(i);
} else {
BigInteger fib = compute(i); // not included here.
cache.putIfAbsent(i, fib);
return fib;
}
}
So, calling Fibonacci.fibonacci(1000) may change the internal state of the target, but it's still the same target.
Now, here's a possible security violation:
public class DateRange {
private Date start;
private Date end;
public DateRange(final Date start, final Date end) {
if (start.after(end)) {
throw new IllegalArgumentException("Range out of order");
}
this.start = start;
this.end = end;
}
public Date getStart() {
return start;
}
// similar for setStart, getEnd, setEnd.
}
The problem is that java.lang.Date is mutable. Someone can write code like:
DateRange range = new DateRange(today, tomorrow);
// In another routine.
Date start = range.getStart();
start.setYear(2088); // Deprecated, I know. So?
Now range is out of order. It's like handing the cashier your wallet.
This is why it is best to do one of these, the earlier ones being preferable.
Have as many objects as possible be immutable. This is why Joda-Time was written, and why dates will chnage yet again in Java 8.
Make defensive copies of items one sets or gets.
Return an immutable wrapper of an item.
Return collections as iterables, not as themselves. Of course, someone might cast it back.
Return a proxy to access the item, that can't be cast to its type.
I know, I know. if I want C or C++, I know where to find them.
1. Return
Related
So, we created a simple class with some private class member and automatically generated getter for it. But getter actually returned a reference to that member, resulting in gaining full access to a private member. Is that okay?
Here's the code of a class:
public class User {
private ArrayList<String> strings = new ArrayList(){ {
add("String1");
add("String2");
} };
public User() {
}
public ArrayList<String> getStrings() {
return strings;
}
public void setStrings(ArrayList<String> strings) {
this.strings = strings;
}
}
Code of main method:
public class Main {
public static void main(String[] args){
User user = new User();
System.out.println(user.getStrings());
user.getStrings().add("String3");
System.out.println(user.getStrings());
}
}
And output:
[String1, String2]
[String1, String2, String3]
I've changed the getter to this one:
public ArrayList<String> getStrings() {
return (ArrayList<String>)strings.clone();
}
But the question remains, what getters are for if not for safety? And what is the right way to write them?
No, it isn't okay because it breaks encapsulation and thus the class can't maintain its own invariants. Same with constructors.
But the problem isn't with getters/setters, it's with the code that autogenerates them.
To cut a long story short: don't use autogenerated accessors blindly, if they're dealing with mutable structures, make defensive copies (or immutable equivalents).
As an aside, I would not have a getter with an ArrayList return type, even if it's just a copy. It's usually none of the client's business what kind of list you're returning, so my getter would look like this:
public List<String> getStrings() {
return new ArrayList<>(strings);
}
Or using an immutable view:
public List<String> getStrings() {
return Collections.unmodifiableList(strings);
}
Or using Guava's ImmutableList class:
public List<String> getStrings() {
return ImmutableList.copyOf(strings);
}
There are subtle differences between the three solutions so which one's best may vary. As a general rule I prefer returning immutable structures because that makes it clear that changes made to the structure won't be reflected, i.e. user.getStrings().add( "X" ); will fail with an exception.
Another subtle problem with the code you showed us is the double braces initialisation. Imagine a class like this:
public class Foo {
private List<String> strings = new ArrayList() {{ add("bar");}};
private Object veryLargeField; //the object stored here consumes a lot of memory
public List<String> getStrings() {
return strings;
}
}
Now imagine we're doing this:
private class Bar {
private List<String> fooStrings;
public Bar() {
this.fooStrings = new Foo().getStrings();
}
}
How much memory would Bar consume (or to use the precise term: retain)? Well, it turns out that quite a lot, because what you do with the double brace initialisation is create an anonymous inner class, which will contain a reference to its outer class (Foo), and thus while the list returned is accessible, all the other fields of Foo will be ineligible for garbage collection.
From my point of view getters usually should serve two purposes:
first they should guard the implementation details.
second they should provide a way to extend easily (e.g. validation or instrumentation)
If your example violates these principles depends on the context:
If your class should own the strings then probably everyone should interact with the container object to modify the list and not with the list itself. To expose a collection (e.g. For processing in a method that expects a collection) you can use e.g. Collections.unmodifiableList(). If on the other hand the class only owns the list of strings then it is not an implementation detail to have a list.
Using a getter instead of directly accessing the fields allows you to easily add data conversation, tracing instrumentation and other things without changing all the places where the field is used.
To make a immutable class , Effective Java has one last condition.
To make a class immutable, follow these five rules:
5- Ensure exclusive access to any mutable components. If your class has any fields that refer to mutable objects, ensure that clients of the class cannot obtain references to these objects. Never initialize such a field to a client-provided object reference nor return the object reference from an accessor. Make defensive copies (Item 24) in contructors, accessors, and readObject methods
public final class ImmutableClass {
private MutableObject mutableObject;
// If I should not provide getter for this object. Then what is the use of this variable after I have
//initalised in the constructor
}
Can somebody explain me this point?
It's actually reasonably simple.
Basically, it's saying to not...
1- Make available any reference to any mutable object that your object might contain.
So if your Class contained a java.util.List as one of it's fields, there should be no way for any client using your Class to gain a reference directly to the List field, either via public deceleration or getter of some kind.
For example...
public class BadImmutableExample {
public List<String> myStrings; // This can not be referenced by the client
/*...*/
}
Would be bad, because the field myStrings is accessible to any body to make modifications to...
In the case you had to return the values in the List you would either be required to return a copy of the List (not a reference to it) or return an array of the values, for example.
For example...
public class BadImmutableExample {
private List<String> myStrings; // This can not be referenced by the client
/*...*/
public List<String> getMyStrings() {
return myStrings;
}
}
Would expose the List myStrings to any clients, which would allow them to modify it.
In this case, you could also use Collections.unmodifiableList(myStrings) to make the list unmodifiable, or return new ArrayList<String>(myStrings) or return an array of String instead...
2- Never initialise such a field to a client provided object...
Basically this means that if your Class requires the client to seed it with some kind of value or values, you should never maintain a reference directly them, instead, again, make a copy for you own reference...
For example...
public class BadImmutableExample {
private List<String> myStrings; // This can not be referenced by the client
public ImmutableExample(List<String> clientStrings) {
myStrings = clientStrings;
}
}
Would break this rule, as any changes to clientStrings would be immediately reflected within you class.
Instead, you could do something like...
public class BetterImmutableExample {
private List<String> myStrings; // This can not be referenced by the client
public ImmutableExample(List<String> clientStrings) {
myStrings = new ArrayList<String>(clientStrings);
}
}
Instead, which will make a copy of the client supplied list, but which will no longer reflect changes made to it (the client supplied list)
Take, for example, immutability. How could I modify an object to indicate that it has been made immutable already and need not be wrapped again?
Let us assume we do not want to use reflection to scan for setters as that would be inefficient and insufficient.
Example:
// Deliberately chosing lowercase because it is a system attribute.
interface immutable {
// Nothing in here I can think of.
}
// immute - have I invented a new word?
// What can I do with the return type to indicate immutability?
public static <T> List<T> immute(List<T> list) {
// If it's not an immutable
if (!(list instanceof immutable)) {
// Make it so - how can I stamp it so?
return Collections.<T>unmodifiableList(list);
}
// It is immutable already.
return list;
}
Further playing with the idea produced this foul solution - it is horrible and almost any other trick would be better but I felt I should post. Please please find a better solution:
public class Test {
// Deliberately chosing lowercase because it is a system attribute.
interface immutable {
// Nothing in here I can think of.
}
// immute - have I invented a new word?
// What can I do with the return type to indicate immutability?
public static <T> List<T> immute(List<T> list) {
// If it's not an immutable
if (!(list instanceof immutable)) {
// Make it so - how can I stamp it so?
return Hacker.hack(Collections.<T>unmodifiableList(list),
List.class,
immutable.class);
}
// It is immutable already - code DOES get here.
return list;
}
public void test() {
System.out.println("Hello");
List<String> test = new ArrayList<>();
test.add("Test");
test("Test", test);
List<String> immutableTest = immute(test);
test("Immutable Test", immutableTest);
List<String> immutableImmutableTest = immute(immutableTest);
test("Immutable Immutable Test", immutableImmutableTest);
}
private void test(String name, Object o) {
System.out.println(name + ":" + o.getClass().getSimpleName() + "=" + o);
}
public static void main(String args[]) {
new Test().test();
}
}
class Hacker {
// Hack an object to seem to implement a new interface.
// New interface should be instanceof testable.
// Suggest the additional type is an empty interface.
public static <T> T hack(final Object hack,
final Class<T> baseType,
final Class additionalType) {
return (T) Proxy.newProxyInstance(
Thread.currentThread().getContextClassLoader(),
new Class[]{baseType, additionalType},
new InvocationHandler() {
#Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// Always invoke the method in the hacked object.
return method.invoke(hack, args);
}
});
}
}
If the check will be done on the same location, you could use a set or map, where you put all your wrapped objects, and check them later on in almost constant time. To avoid memory leaks, you could wrap them using weak references .
If the introduction of AOP is a (rather heavyweight) option, you could solve your problem using inter type declarations via AspectJ. This way, you could just add a private member with the reference to the corresponding wrapped instance to the Collection interface, if I remember correctly something like this:
aspect Unmodifieable {
private Collection java.util.Collection.unmofifieableWrapper = null;
public Collection java.util.Collection.getUnmodifieable() {
if (unmofifieableWrapper == null) {
unmofifieableWrapper = somehowRetrieveUnmodifieableCollection(this);
}
return unmofifieableWrapper;
}
}
You can do this with naming conventions in your classes.
interface MyObject;
class MyMutableObject implements MyObject;
class MyImmutableObject implements MyObject;
In my current project, I do something similar. I have an interface that needs to have a setter, but one of the implementing classes is immutable. When you call its setter it throws an Exception (it's setter should never be called, but it's there just to be safe).
The "information" you're looking for is more for the programmer than the compiler, so you don't need a language implemented "stamp".
The Collections.unmodifiable* methods return subtypes of UnmodifiableCollection so you could check UnmodifiableCollection.class.isAssignableFrom(list) then test the concrete types.
Without using instrumentation, I think you're stuck checking types.
I need to manage data in my program where Java-Vector suits the purpose as it is synchronized,provides dynamic size and fast random access through index.
But I want to make my Vector Read Only for other Program Classes and Read Write for my own Class.
I read about Collections.unmodifiableList() ,but if I make my Vector unmodifiable, it will become read-only to my class as well.
How can I solve this problem?
I read about Collections.unmodifiableList(), but if I make my Vector unmodifiable, it will become read-only to my class as well.
I think you misunderstand what that method does. In reality, it creates an unmodifiable wrapper for the existing list, leaving the original list modifiable.
So the way to handle your requirement is to do something like this1:
private Vector<?> myVector = new Vector<?>();
private List<?> readOnly = Collections.Collections.unmodifiableList((myVector);
public List<?> getList() { return readOnly; }
Anything that has access to myVector can still add and remove elements from it. The changes will be visible via the readonly object ... but "change" operations on that object won't work.
(The other approach is to create copies of the original Vector object, but I'm pretty sure that doesn't meet your requirements.)
1 - Note that the readOnly object is a List but not a Vector. This shouldn't be a problem unless you have made the mistake of declaring the getter as returning a Vector. If you've done that, and you can't correct the mistake, then you will need to create your own subclass of Vector along the line of Evgeniy Dorofeev's answer. Otherwise Collections.unmodifiableList(...) will do just fine.
Make it a private member of your class and only provide getters that return an immutable version of the vector as a public way to access it, using the function you mentioned (Collections.unmodifiableList()).
If you really want an unmodifiable Vector (not just List) create a method as
public static Vector unmodifiableVector(Vector v) {
return new Vector(v) {
#Override
public void add(int index, Object element) {
throw new UnsupportedOperationException();
}
#Override
public synchronized boolean addAll(Collection c) {
#Override
public synchronized void addElement(Object obj) {
// ... other mutators
}
}
try this:
Collections.unmodifiableList(myList);
Make vector a private member of your class. expose a public method to the callers which will get a reference to an unmodifiableCollection.
public Vector getVector(){
return Collections.unmodifiableList(yourVector) ;
}
For use in your internal class, you can either reference the vector directly or create a private method which will return a reference to collection.
private Vector getMyVector(){
return yourVector ;
}
I think if you make your Vector as private member attribute in your along with all write methods as private while read methods as public, you would be OK e.g.
private Vector<T> myVector = ...
private void setMyVector(Vector<T> vector){
myVector = vector;
}
private void addElement(T element){
myVector.add(element);
}
public T getElement(int indx){
return myVector.get(indx);
}
....
....
By making the vector instance as private and providing setter as private with getter as public would be the correct path in my opinion.
For the :
List<T> readOnlyList = Collections.unmodifiableList(myList);
it will readnoly instance, however, it will still allow the access to other classes to call add/set/remove methods but calling these methods results in UnsupportedException being raised.
Also, based on your requirement, you are looking for the updation of the vector / addition of new elements in it. So may by look for concurrent package to make it safer in doing so.
Its better to give copy of your Vector rather than giving original reference of your Vector Like following:
Vector vector = // your vector object in your class
public Vector<String> getMyVercorObject(){
return (Vector<String>)vector.clone() ;
}
The best way is to use Vector internally, only expose mutations (add, remove, etc) using methods, and only return an unmodifiable view using an interface (List). Such an implementation might look like this (for example sake let's say the elements are strings):
private final List<String> list = new Vector<String>();
/** Adds the specified element. */
public void addElement(String element) {
list.add(element);
}
/** Replaces all elements. */
public void setElements(List<String> newElements) {
list.clear();
list.addAll(newElements);
}
/** Returns all elements. */
public List<String> getElement() {
return Collections.unmodifiableList(list);
}
In this way your class has full access to the list, while external entities can only mutate using the public methods.
Note that Vector is pretty much not used. If you require a thread safe list then consider ArrayList in conjunction with synchronizedList:
private final List<String> list = Collections.synchronizedList(new ArrayList<String>());
final public class ImmutableWithObject {
final Object obj;
final List myList;
ImmutableWithObject(Object obj1, List list)
{
this.obj = obj1;
this.myList = ((List) ((ArrayList) list).clone());
}
public Object getObj() {
return this.obj;
}
public List getMyList() {
return (List) ((ArrayList<String>) this.myList).clone();
}
public static void main(String[] args) {
ImmutableWithObject io = new ImmutableWithObject(new Date(), new ArrayList());
((Date) io.getObj()).setDate(22);
System.out.println((Date) io.getObj());
}
}
o/p : Mon Aug 22 00:50:04 IST 2011
which is incorrect.
Immutable means that once the object has been constructed, its state does not change.
Make class final ( which you have already done )
Make the instance variables as private and final
Dont provide methods that change the state
When passing instance variables, send copies instead of original.
From EJ Item 15 <-- Lot more information in there
Classes should be immutable unless there's a very good reason to make them mutable. If a class cannot be made immutable, limit its mutability as much as possible.
You cannot make it immutable since this object cannot create copies of the contents of the list or the Object. Assuming that you mean to have getters for accessing those properties, the properties themselves were created elsewhere and can be changed in code external to this class that has a reference to it.
The only exception to this is if the contents of Object and List are themselves immutable. Then you can create an immutable copy of the list and you would be done.
You can make a copy of the values of the List object. Whoever called it still has that List and can modify it.
Make the member variables private final and copy the parameters:
final class ImmutableWithObject {
private final Object obj;
private final List myList;
public ImmutableWithObject(Object obj1 , List list)
{
this.obj = obj1.clone();
this.list = (List) list.clone();
}
}
This will not allow any other class to change your internal state and will not allow ImmutableWithobject to change the myList or obj references. However the obj's state as well as the list can still be manipulated internally. As others pointed out, whoever past the list or obj1 to you class, would be able to manipulate it from the outside too. Since there is no equivalent of something like const in C++, we will have to copy the objects to make sure they are not changed from the outside.
Similarly, if there was a getter, it should also only return a copy (or some read-only interface or a read-only wrapper):
public Object getObj() { return obj.clone(); }