I am unable to get what are the scenarios where we need an immutable class.
Have you ever faced any such requirement? or can you please give us any real example where we should use this pattern.
The other answers seem too focused on explaining why immutability is good. It is very good and I use it whenever possible. However, that is not your question. I'll take your question point by point to try to make sure you're getting the answers and examples you need.
I am unable to get what are the scenarios where we need an immutable class.
"Need" is a relative term here. Immutable classes are a design pattern that, like any paradigm/pattern/tool, is there to make constructing software easier. Similarly, plenty of code was written before the OO paradigm came along, but count me among the programmers that "need" OO. Immutable classes, like OO, aren't strictly needed, but I going to act like I need them.
Have you ever faced any such requirement?
If you aren't looking at the objects in the problem domain with the right perspective, you may not see a requirement for an immutable object. It might be easy to think that a problem domain doesn't require any immutable classes if you're not familiar when to use them advantageously.
I often use immutable classes where I think of a given object in my problem domain as a value or fixed instance. This notion is sometimes dependent on perspective or viewpoint, but ideally, it will be easy to switch into the right perspective to identify good candidate objects.
You can get a better sense of where immutable objects are really useful (if not strictly necessary) by making sure you read up on various books/online articles to develop a good sense of how to think about immutable classes. One good article to get you started is Java theory and practice: To mutate or not to mutate?
I'll try to give a couple of examples below of how one can see objects in different perspectives (mutable vs immutable) to clarify what I mean by perspective.
... can you please give us any real example where we should use this pattern.
Since you asked for real examples I'll give you some, but first, let's start with some classic examples.
Classic Value Objects
Strings and integers are often thought of as values. Therefore it's not surprising to find that String class and the Integer wrapper class (as well as the other wrapper classes) are immutable in Java. A color is usually thought of as a value, thus the immutable Color class.
Counterexample
In contrast, a car is not usually thought of as a value object. Modeling a car usually means creating a class that has changing state (odometer, speed, fuel level, etc). However, there are some domains where it car may be a value object. For example, a car (or specifically a car model) might be thought of as a value object in an app to look up the proper motor oil for a given vehicle.
Playing Cards
Ever write a playing card program? I did. I could have represented a playing card as a mutable object with a mutable suit and rank. A draw-poker hand could be 5 fixed instances where replacing the 5th card in my hand would mean mutating the 5th playing card instance into a new card by changing its suit and rank ivars.
However, I tend to think of a playing card as an immutable object that has a fixed unchanging suit and rank once created. My draw poker hand would be 5 instances and replacing a card in my hand would involve discarding one of those instance and adding a new random instance to my hand.
Map Projection
One last example is when I worked on some map code where the map could display itself in various projections. The original code had the map use a fixed, but mutatable projection instance (like the mutable playing card above). Changing the map projection meant mutating the map's projection instance's ivars (projection type, center point, zoom, etc).
However, I felt the design was simpler if I thought of a projection as an immutable value or fixed instance. Changing the map projection meant having the map reference a different projection instance rather than mutating the map's fixed projection instance. This also made it simpler to capture named projections such as MERCATOR_WORLD_VIEW.
Immutable classes are in general much simpler to design, implement and use correctly. An example is String: the implementation of java.lang.String is significantly simpler than that of std::string in C++, mostly due to its immutability.
One particular area where immutability makes an especially big difference is concurrency: immutable objects can safely be shared among multiple threads, whereas mutable objects must be made thread-safe via careful design and implementation - usually this is far from a trivial task.
Update: Effective Java 2nd Edition tackles this issue in detail - see Item 15: Minimize mutability.
See also these related posts:
non-technical benefits of having string-type immutable
Downsides to immutable objects in Java?
Effective Java by Joshua Bloch outlines several reasons to write immutable classes:
Simplicity - each class is in one state only
Thread Safe - because the state cannot be changed, no synchronization is required
Writing in an immutable style can lead to more robust code. Imagine if Strings weren't immutable; Any getter methods that returned a String would require the implementation to create a defensive copy before the String was returned - otherwise a client may accidentally or maliciously break that state of the object.
In general it is good practise to make an object immutable unless there are severe performance problems as a result. In such circumstances, mutable builder objects can be used to build immutable objects e.g. StringBuilder
Hashmaps are a classic example. It's imperative that the key to a map be immutable. If the key is not immutable, and you change a value on the key such that hashCode() would result in a new value, the map is now broken (a key is now in the wrong location in the hash table.).
Java is practically one and all references. Sometimes an instance is referenced multiple times. If you change such an instance, it would be reflected into all its references. Sometimes you simply don't want to have this to improve robustness and threadsafety. Then an immutable class is useful so that one is forced to create a new instance and reassign it to the current reference. This way the original instance of the other references remain untouched.
Imagine how Java would look like if String was mutable.
Let's take an extreme case: integer constants. If I write a statement like "x=x+1" I want to be 100% confidant that the number "1" will not somehow become 2, no matter what happens anywhere else in the program.
Now okay, integer constants are not a class, but the concept is the same. Suppose I write:
String customerId=getCustomerId();
String customerName=getCustomerName(customerId);
String customerBalance=getCustomerBalance(customerid);
Looks simple enough. But if Strings were not immutable, then I would have to consider the possibility that getCustomerName could change customerId, so that when I call getCustomerBalance, I am getting the balance for a different customer. Now you might say, "Why in the world would someone writing a getCustomerName function make it change the id? That would make no sense." But that's exactly where you could get in trouble. The person writing the above code might take it as just obvious that the functions would not change the parameter. Then someone comes along who has to modify another use of that function to handle the case where where a customer has multiple accounts under the same name. And he says, "Oh, here's this handy getCustomer name function that's already looking up the name. I'll just make that automatically change the id to the next account with the same name, and put it in a loop ..." And then your program starts mysteriously not working. Would that be bad coding style? Probably. But it's precisely a problem in cases where the side effect is NOT obvious.
Immutability simply means that a certain class of objects are constants, and we can treat them as constants.
(Of course the user could assign a different "constant object" to a variable. Someone can write
String s="hello";
and then later write
s="goodbye";
Unless I make the variable final, I can't be sure that it's not being changed within my own block of code. Just like integer constants assure me that "1" is always the same number, but not that "x=1" will never be changed by writing "x=2". But I can be confidant that if I have a handle to an immutable object, that no function I pass it to can change it on me, or that if I make two copies of it, that a change to the variable holding one copy will not change the other. Etc.
We don't need immutable classes, per se, but they can certainly make some programming tasks easier, especially when multiple threads are involved. You don't have to perform any locking to access an immutable object, and any facts that you've already established about such an object will continue to be true in the future.
There are various reason for immutability:
Thread Safety: Immutable objects cannot be changed nor can its internal state change, thus there's no need to synchronise it.
It also guarantees that whatever I send through (through a network) has to come in the same state as previously sent. It means that nobody (eavesdropper) can come and add random data in my immutable set.
It's also simpler to develop. You guarantee that no subclasses will exist if an object is immutable. E.g. a String class.
So, if you want to send data through a network service, and you want a sense of guarantee that you will have your result exactly the same as what you sent, set it as immutable.
My 2 cents for future visitors:
2 scenarios where immutable objects are good choices are:
In multi-threading
Concurrency issues in multi-threaded environment can very well be solved by synchronization but synchronization is costly affair (wouldn't dig here on "why"), so if you are using immutable objects then there is no synchronization to solve concurrency issue because state of immutable objects cannot be changed, and if state cannot be changed then all threads can seamless access the object. So, immutable objects makes a great choice for shared objects in multi-threaded environment.
As key for hash based collections
One of the most important thing to note when working with hash based collection is that key should be such that its hashCode() should always return the same value for the lifetime of the object, because if that value is changed then old entry made into the hash based collection using that object cannot be retrieved, hence it would cause memory leak. Since state of immutable objects cannot be changed so they makes a great choice as key in hash based collection. So, if you are using immutable object as key for hash based collection then you can be sure that there will not be any memory leak because of that (of course there can still be memory leak when the object used as key is not referenced from anywhere else, but that's not the point here).
I'm going to attack this from a different perspective. I find immutable objects make life easier for me when reading code.
If I have a mutable object I am never sure what its value is if it's ever used outside of my immediate scope. Let's say I create MyMutableObject in a method's local variables, fill it out with values, then pass it to five other methods. ANY ONE of those methods can change my object's state, so one of two things has to occur:
I have to keep track of the bodies of five additional methods while thinking about my code's logic.
I have to make five wasteful defensive copies of my object to ensure that the right values get passed to each method.
The first makes reasoning about my code difficult. The second makes my code suck in performance -- I'm basically mimicking an immutable object with copy-on-write semantics anyway, but doing it all the time whether or not the called methods actually modify my object's state.
If I instead use MyImmutableObject, I can be assured that what I set is what the values will be for the life of my method. There's no "spooky action at a distance" that will change it out from under me and there's no need for me to make defensive copies of my object before invoking the five other methods. If the other methods want to change things for their purposes they have to make the copy – but they only do this if they really have to make a copy (as opposed to my doing it before each and every external method call). I spare myself the mental resources of keeping track of methods which may not even be in my current source file, and I spare the system the overhead of endlessly making unnecessary defensive copies just in case.
(If I go outside of the Java world and into, say, the C++ world, among others, I can get even trickier. I can make the objects appear as if they're mutable, but behind the scenes make them transparently clone on any kind of state change—that's copy-on-write—with nobody being the wiser.)
Immutable objects are instances whose states do not change once initiated.
The use of such objects is requirement specific.
Immutable class is good for caching purpose and it is thread safe.
By the virtue of immutability you can be sure that the behavior/state of the underlying immutable object do not to change, with that you get added advantage of performing additional operations:
You can use multiple core/processing(concurrent/parallel processing) with ease(as the sequence of operations will no longer matter.)
Can do caching for expensive operations (as you are sure of the same
result).
Can do debugging with ease(as the history of run will not be a concern
anymore)
Using the final keyword doesn't necessarily make something immutable:
public class Scratchpad {
public static void main(String[] args) throws Exception {
SomeData sd = new SomeData("foo");
System.out.println(sd.data); //prints "foo"
voodoo(sd, "data", "bar");
System.out.println(sd.data); //prints "bar"
}
private static void voodoo(Object obj, String fieldName, Object value) throws Exception {
Field f = SomeData.class.getDeclaredField("data");
f.setAccessible(true);
Field modifiers = Field.class.getDeclaredField("modifiers");
modifiers.setAccessible(true);
modifiers.setInt(f, f.getModifiers() & ~Modifier.FINAL);
f.set(obj, "bar");
}
}
class SomeData {
final String data;
SomeData(String data) {
this.data = data;
}
}
Just an example to demonstrate that the "final" keyword is there to prevent programmer error, and not much more. Whereas reassigning a value lacking a final keyword can easily happen by accident, going to this length to change a value would have to be done intentionally. It's there for documentation and to prevent programmer error.
Immutable data structures can also help when coding recursive algorithms. For example, say that you're trying to solve a 3SAT problem. One way is to do the following:
Pick an unassigned variable.
Give it the value of TRUE. Simplify the instance by taking out clauses that are now satisfied, and recur to solve the simpler instance.
If the recursion on the TRUE case failed, then assign that variable FALSE instead. Simplify this new instance, and recur to solve it.
If you have a mutable structure to represent the problem, then when you simplify the instance in the TRUE branch, you'll either have to:
Keep track of all changes you make, and undo them all once you realize the problem can't be solved. This has large overhead because your recursion can go pretty deep, and it's tricky to code.
Make a copy of the instance, and then modify the copy. This will be slow because if your recursion is a few dozen levels deep, you'll have to make many many copies of the instance.
However if you code it in a clever way, you can have an immutable structure, where any operation returns an updated (but still immutable) version of the problem (similar to String.replace - it doesn't replace the string, just gives you a new one). The naive way to implement this is to have the "immutable" structure just copy and make a new one on any modification, reducing it to the 2nd solution when having a mutable one, with all that overhead, but you can do it in a more efficient way.
One of the reasons for the "need" for immutable classes is the combination of passing everything by reference and having no support for read-only views of an object (i.e. C++'s const).
Consider the simple case of a class having support for the observer pattern:
class Person {
public string getName() { ... }
public void registerForNameChange(NameChangedObserver o) { ... }
}
If string were not immutable, it would be impossible for the Person class to implement registerForNameChange() correctly, because someone could write the following, effectively modifying the person's name without triggering any notification.
void foo(Person p) {
p.getName().prepend("Mr. ");
}
In C++, getName() returning a const std::string& has the effect of returning by reference and preventing access to mutators, meaning immutable classes are not necessary in that context.
They also give us a guarantee. The guarantee of immutability means that we can expand on them and create new patters for efficiency that are otherwise not possible.
http://en.wikipedia.org/wiki/Singleton_pattern
One feature of immutable classes which hasn't yet been called out: storing a reference to a deeply-immutable class object is an efficient means of storing all of the state contained therein. Suppose I have a mutable object which uses a deeply-immutable object to hold 50K worth of state information. Suppose, further, that I wish to on 25 occasions make a "copy" of my original (mutable) object (e.g. for an "undo" buffer); the state could change between copy operations, but usually doesn't. Making a "copy" of the mutable object would simply require copying a reference to its immutable state, so 20 copies would simply amount to 20 references. By contrast, if the state were held in 50K worth of mutable objects, each of the 25 copy operations would have to produce its own copy of 50K worth of data; holding all 25 copies would require holding over a meg worth of mostly-duplicated data. Even though the first copy operation would produce a copy of the data that will never change, and the other 24 operations could in theory simply refer back to that, in most implementations there would be no way for the second object asking for a copy of the information to know that an immutable copy already exists(*).
(*) One pattern that can sometimes be useful is for mutable objects to have two fields to hold their state--one in mutable form and one in immutable form. Objects can be copied as mutable or immutable, and would begin life with one or the other reference set. As soon as the object wants to change its state, it copies the immutable reference to the mutable one (if it hasn't been done already) and invalidates the immutable one. When the object is copied as immutable, if its immutable reference isn't set, an immutable copy will be created and the immutable reference pointed to that. This approach will require a few more copy operations than would a "full-fledged copy on write" (e.g. asking to copy an object which has been mutated since the last copy would require a copy operation, even if the original object is never again mutated) but it avoids the threading complexities that FFCOW would entail.
Why Immutable class?
Once an object is instantiated it state cannot be changed in lifetime. Which also makes it thread safe.
Examples :
Obviously String, Integer and BigDecimal etc. Once these values are created cannot be changed in lifetime.
Use-case :
Once Database connection object is created with its configuration values you might not need to change its state where you can use an immutable class
from Effective Java;
An immutable class is simply a class whose instances cannot be modified. All of
the information contained in each instance is provided when it is created and is
fixed for the lifetime of the object. The Java platform libraries contain many
immutable classes, including String, the boxed primitive classes, and BigInte-
ger and BigDecimal. There are many good reasons for this: Immutable classes
are easier to design, implement and use than mutable classes. They are less prone
to error and are more secure.
An immutable class is good for caching purposes because you don't have to worry about the value changes. Another benefit of an immutable class is that it is inherently thread-safe, so you don't have to worry about thread safety in case of a multi-threaded environment.
I'm fairly new to Java so my knowledge is pretty limited. I'm working on a personal project where I'm trying out some of the techniques used in Guava for creating views/transformations of collections. I made a class called View to take an inputted collection as the backing iterable, and a transformation, and then present it as a read-only iterable. (not a collection, though I don't think it makes much of a difference for this question). Here is a quick example of using it...
public class Node {
public enum Change implements Function<Node, Coordinate> {
TO_COORDINATE;
#Override public Coordinate apply(Node node) {
return new Coordinate(node);
}
}
private HashSet<Node> neighborNodes = new HashSet<Node>();
//various other members
public View<Coordinate> viewNeighborCoordinates() {
return new View<Coordinate>(neighborNodes, Change.TO_COORDINATE);
}
}
now if some method wants to use viewNeighborCoordinates() of this node, and then later some other method also wants to viewNeighborCoordinates() of this node, it seems wasteful to always be returning new objects, right? I mean any number of things should be able to share reference to a view of the same backing iterable with the same transformation, since all they're doing is reading through it. Is there an established way of managing a shared pool of objects which can be "interned" like Strings are? Is it just having to make some sort of ViewFactory that stores a running list of views in use, and everytime someone wants a view, it checks to see if it already has that view and hands it out? (is that even more efficient)?
As already stated, interning is possible (look at Interners), but most probably a bad idea.
Another possibility is lazy initialization of a field storing the View. Since I'm lazy as well, I only point you to a Lombok implementation. Be careful with DCL, if you want to try this. In case your class is immutable, you may need no synchronization at all, like e.g. String.hashCode.
A very simple possibility is eager initialization of a field. Assuming you need the view often, it's the best way.
But without knowing more, your current implementation is best. Beware the root of all evil.
Don't optimize without profiling or benchmarking (and if you benchmark, then do it right, i.e., using caliper or jmh. Home-baked benchmarking in Java just doesn't work).
I just read some code written by a more experienced programmer, and I came across the following:
public class ConsoleFormatter extends Formatter {
private static final Map<Level, String> PREFIXES;
static {
Map<Level, String> prefixes = new HashMap<Level, String>();
prefixes.put(Level.CONFIG, "[config]");
prefixes.put(Level.FINE, "[debug]");
prefixes.put(Level.FINER, "[debug]");
prefixes.put(Level.FINEST, "[trace]");
prefixes.put(Level.INFO, "[info]");
prefixes.put(Level.SEVERE, "[error]");
prefixes.put(Level.WARNING, "[warning]");
PREFIXES = Collections.unmodifiableMap(prefixes);
}
// ...
}
As you can see, this is a class used for formatting log output. What caught my eye, however, was the code in the static initializer block: PREFIXES = Collections.unmodifiableMap(prefixes);.
Why was PREFIXES made an unmodifiable map? It's a private constant, so there's no risk of modifying the data outside of that class. Was it done to give the constant's immutability a sense of completeness?
Personally, I would've directly initialized PREFIXES as a HashMap and then put the key–value pairs in directly, without creating a dummy, placeholder map or making the field an immutable map. Am I missing something here?
By making the list unmodifiable the author documented his assumption that the values will never change. Whoever might edit that class later on can not only see that assumption, but will also be reminded in case it is ever broken.
This makes sense only when taking the longer-term view. It reduces the risk of new problems arising through maintenance. I like to do this style of programming, because I tend to break stuff even in my own classes. One day you might go in for a quick fix and you forget about an assumption that was made originally and is relevant for correctness. The more you can lock the code down, the better.
If you accidentally return PREFIXES from a method, suddenly any other code out there can modify it. Making constants truly immutable defends against your own stupidity when you modify that code in the future at 3AM.
It's surprisingly easy to have a private map, collection or array which is modifiable from outside the class. You'd mark it final, why wouldn't also spell out that it is supposed to be immutable as well?
Suppose your friend leaves his job and a less experienced programmer takes over. The less experienced programmer attempts to modify the contents of PREFIXES somewhere in a different method within the same class. It it's unmodifiable, it won't work. It's the proper way to say "this is a constant, don't ever change it."
The Map interface does not communicate that you want something to be immutable or unmodifiable.
The following approaches will work in Eclipse Collections.
private static final ImmutableMap<Level, String> PREFIXES = UnifiedMap.<Level, String>newMap()
.withKeyValue(Level.CONFIG, "[config]")
.withKeyValue(Level.FINE, "[debug]")
.withKeyValue(Level.FINER, "[debug]")
.withKeyValue(Level.FINEST, "[trace]")
.withKeyValue(Level.INFO, "[info]")
.withKeyValue(Level.SEVERE, "[error]")
.withKeyValue(Level.WARNING, "[warning]")
.toImmutable();
This will create a Map that is contractually immutable, because ImmutableMap has no mutating methods in its API.
If you prefer to to keep the Map interface, this approach will work as well.
private static final Map<Level, String> PREFIXES = UnifiedMap.<Level, String>newMap()
.withKeyValue(Level.CONFIG, "[config]")
.withKeyValue(Level.FINE, "[debug]")
.withKeyValue(Level.FINER, "[debug]")
.withKeyValue(Level.FINEST, "[trace]")
.withKeyValue(Level.INFO, "[info]")
.withKeyValue(Level.SEVERE, "[error]")
.withKeyValue(Level.WARNING, "[warning]")
.asUnmodifiable();
You should notice there is no need for the static block in either of the cases.
Note: I am a committer for Eclipse Collections.
If a collection is made final, you cannot set a new object into it.
However, it is still possible to add or remove items to the same object.
When you make it unmodifiable, you cannot even add or remove items to the collection.
Hence, it is always advised to make the collection Unmodifiable instead of just keeping it as final.
I would like to create a base class that all classes in my program will extend. One thing I wanted to do was find a uniform way to store all instance variables inside the object.
What I have come up with is to use a HashMap to store the key/value pairs for the object and then expose those values through a get and set method.
The code that I have for this so far is as follows:
package ocaff;
import java.util.HashMap;
public class OcaffObject {
private HashMap<String, Object> data;
public OcaffObject() {
this.data = new HashMap<String, Object>();
}
public Object get(String value) {
return this.data.get(value);
}
public void set(String key, Object value) {
this.data.put(key, value);
}
}
While functionally this works, I am curious if there are any real issues with this implementation or if there is a better way to do this?
In my day to day work I am a PHP programmer and my goal was to mimic functionality that I used in PHP in Java.
I don't think this is a good way to deal with what you mean.
Programming in java is quite different than programming in php, from my point of view.
You need to keep things clean and strongly typed, using the real paradigm of clean object oriented programming.
Some problems with this technique comes to my mind, here are some, not in importance order.
First problem you have with this is performance and memory footprint: this will consume a lot of memory and will perform very badly.
Second problem is concurrency, HashMap is not thread safe.
Third problem is type safety: you don't have type safety anymore, you can write to a field whatever you want and no one is checking it, a real anti-pattern.
Fourth problem is debugging... it will be hard to debug your code.
Fifth problem is: everyone can write and read any field knowing his name.
Sixth problem: when you change the name of a field in the hash set you don't get any kind of compile time error, you only get strange run-time behavior. Refactoring will become impossible.
Typed fields are much more useful and clean.
If you're taking the time to make a class for this, I would simply add what you need as members of the class. This will give you compile time checking of your class members, greatly reducing your subtle bugs.
This might seem to be a strange question: I am struggling to decide whether it is a good practice and "efficient" to work with "Typed Objects" on a very granular level.
public Object[] doSomething() {
Object[] resultList = new Object[] {new Foo(), new Bar()};
return resultList;
}
versus
public Result doSomething() {
Result result = new Result();
result.foo = new Foo();
result.bar = new Bar();
return result;
}
public class Result{
Foo foo;
Bar bar;
}
My question is concrete as follows:
In terms of CPU Cycles (as a relative figure), how much does the second approach consume more resources. (like 100% more)
The same question in regard to memory consumption
NB (these two are questions to understand it more, its not about premature optimization)
In terms of "good design practice". Do you think version 1 is an absolute No-Go or do you rather think it actually does not matter...Or would you propose never returning "object Arrays" (((in an object oriented programming language)))...
This is something, I am always wondering if I should create dedicated Objects for everything (for passing values) or I should rather use generic objects (and common method parameters...)
The question also applies to
public doSomething(Query query )
versus
public doSomething(Foo foo, Bar bar, Aaaa, a, Bbbbb)
thanks
Markus
3.) In terms of "good design pratice". Do you think version 1 is an absolute No-Go or do you rather think it actually does not matter...Or would you propose never returnung "object Arrays" (((in an object oriented programming langauge/regarding encapsulation ...)))...
Version 1 is absolutely a no-go. It's almost completely untyped. The caller has to know the actual types and where they are in the array, and cast appropriately. You lose any useful compile-time type checking, and the code itself is significantly less clear.
I would never return an Object[] unless the values it contained were constructed with new Object().
I don't believe that defining a Result class and returning that consumes any more resources at run time than constructing an Object[]. (Granted, there's a miniscule cost for storing and loading the class definition.) Do you have data that indicate otherwise?
Returning an untyped object array is poor practice for various reasons, among which are:
It's prone to error.
It's harder to maintain.
Casting back to the "real" type is not free, either.
Regarding your other query:
public doSomething(Query query)
versus
public doSomething(Foo foo, Bar bar)
This is less clear-cut. If packaging up a Foo and a Bar into a Query object makes sense in the problem domain, then I would definitely do it. If it's just a packaging up for the sake of minimizing the number of arguments (that is, there's no "query object" concept in your problem domain), then I would probably not do it. If it's a question of run-time performance, then the answer is (as always) to profile.
I'd have to do an experiment to really know, but I'd guess that the object array would not be significantly faster. It might even be slower. After all, in either case you have to create an object: either the array object or the Result object. With the Result object you have to read the class definition from disk the first time you use it, and the class definition has to float around in memory, so there'd be some extra cost there. But with the array object you have to do casts when you pull the data out, and the JVM has to do bounds checkings on the array (What happens if the caller tries to retrieve resultList[12]?), which also involves extra work. My guess is that if you do it only once or twice, the array would be faster (because of the class load time), but if you do it many times, the dedicated object would be faster (because of the cast and array access time). But I admit I'm just guessing.
In any case, even if the array does have a slight performance edge, the loss in readability and maintainability of the code almost surely isn't worth it.
The absolute worst thing that can happen is if values you're returning in the array are of the same class but have different semantic meanings. Like suppose you did this:
public Object[] getCustomerData(int customerid)
{
String customerName=... however you get it ...
BigDecimal currentDue=...
BigDecimal pastDue=...
return new Object[] {customerName, pastDue, currentDue};
}
... meanwhile, back at the ranch ...
Object[] customerData=getCustomerData(customerid);
BigDecimal pastDue=(BigDecimal)customerData[2];
if (pastDue>0)
sendNastyCollectionLetter();
Do you see the error? I retrieve entry #2 as pastDue when it's supposed to be #1. You could easily imagine this happenning if a programmer in a moment of thoughtlessness counted the fields starting from one instead of zero. Or in a long list if he miscounted and said #14 when it's really #15. As both have the same data type, this will compile and run just fine. But we'll be sending inappropriate collection letters to customers who are not over due. This would be very bad for customer relations.
Okay, maybe this is a bad example -- I just pulled it off the top of my head -- because we would be likely to catch that in testing. But what if the values we switched were rarely used, so that no one thought to include a test scenario for them. Or their effect was subtle, so that an error might slip through testing. For that matter, maybe you wouldn't catch this one in testing if you were rushing a change through, or if the tester slipped up, etc etc.