This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Why do Collections(save Arrays) allow only Objects? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Why do Collections(save Arrays) allow only Objects?" Watch "Why do Collections(save Arrays) allow only Objects?" New topic
Author

Why do Collections(save Arrays) allow only Objects?

Monu Tripathi
Rancher

Joined: Oct 12, 2008
Posts: 1365

What's the raison d'etre? Primitives are wrapped; why the normalization?

Thanks.


[List of FAQs] | [Android FAQ] | [My Blog] | [Samuh Varta]
Embla Tingeling
Ranch Hand

Joined: Oct 22, 2009
Posts: 237
Monu Tripathi wrote:What's the raison d'etre? Primitives are wrapped; why the normalization?


There are no collections for primitives in the Sun Java libraries but there have been attempts by other parties to introduce them, like here,

http://sourceforge.net/projects/pcj/

Such attempts haven't been very successful though. I guess it's because it's hard to compete with the "standard" Java library from Sun. People tend to look at what's available there and if something's missing they just accept that without looking further elsewhere. Also the introduction of autoboxing has lessen the need for special collections for primitives.

I've never seen any good explanation as to why Sun hasn't introduced them in the first place. Maybe it is to discourage the use of primitives in general Java usage, I don't know.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32704
    
    4
An array isn't a Collection.

What you put into a collection is a reference to an object; if you put primitives in them, you would end up with pointers to incorrect memory locations. It would be impossible to distinguish 123456 representing a memory location from 123456 the number when values are retrieved from a collection.

Boxing which you allude to only became available in Autumn 2004, by which time Java had been around for >8 years.
Monu Tripathi
Rancher

Joined: Oct 12, 2008
Posts: 1365

An array isn't a Collection.

I think it is and one of the oldest;
Boxing which you allude to only became available in Autumn 2004, by which time Java had been around for >8 years.

yep, earlier you just could not add primitives directly without using wrappers
What you put into a collection is a reference to an object; if you put primitives in them, you would end up with pointers to incorrect memory locations. It would be impossible to distinguish 123456 representing a memory location from 123456 the number when values are retrieved from a collection.

hmmm..so the constraint is because of the way collections are implemented
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32704
    
    4
No an array is not a Collection in the sense that there is a Collection class (well interface, more precisely). It is a much more basic sort of collection (small c) which can be implemented by mimicking the architecture of the hardware. Arrays are usually implemented by putting their elements into adjacent or regularly-spaced memory locations and can use relative indexing at the level of the CPU to find them.

Relative indexing means you give the chip the location of the 1st member of the array and an offset (eg for myArray[99] the offset is 99) and it adds the offset to the memory location and looks there.

As well as the problems about confusing memory locations and int values in a Collection, imagine what would happen if you entered ints and tried to retrieve floats.

I wasn't around when they wrote Java, but I can imagine it didn't take much thinking for them to design Collections to accept only Objects. And remember that in the first versions of Java there were few classes, probably only Hashtable Vector and Stack available. Remember all those classes hide their implementation, but are based on arrays.
Embla Tingeling
Ranch Hand

Joined: Oct 22, 2009
Posts: 237
Campbell Ritchie wrote:An array isn't a Collection.


It definately is in the general sense.


What you put into a collection is a reference to an object; if you put primitives in them, you would end up with pointers to incorrect memory locations. It would be impossible to distinguish 123456 representing a memory location from 123456 the number when values are retrieved from a collection.


You're presenting a specific implementation and then immediately discard it as unsuccessful. What's that supposed to demonstrate? That an implementation is impossible just because you couldn't come up with something working?

And who says the same collection implementation must be able to handle both primitives and references? You can have a separate collections set for each case. The distinction between primitives and references is there and there's no reason why exactly the collections must treat them uniformly.
Monu Tripathi
Rancher

Joined: Oct 12, 2008
Posts: 1365

No an array is not a Collection in the sense that there is a Collection class (well interface, more precisely). It is a much more basic sort of collection (small c) which can be implemented by mimicking the architecture of the hardware.

I "C" what you are trying to say. It is a collection and not a Collection.
Arrays are usually implemented by putting their elements into adjacent or regularly-spaced memory locations and can use relative indexing at the level of the CPU to find them.

Relative indexing means you give the chip the location of the 1st member of the array and an offset (eg for myArray[99] the offset is 99) and it adds the offset to the memory location and looks there.

I am aware of this.
Relative addressing is very "apparent" in C(at language level as well), where you do pointer arithmetic to get to memory locations. For example, assuming array elements take up contiguous memory space, a[100] is equivalent to *(a+100) where a = base address of the array.
As well as the problems about confusing memory locations and int values in a Collection, imagine what would happen if you entered ints and tried to retrieve floats.

I understand your point.

Jesper de Jong
Java Cowboy
Bartender

Joined: Aug 16, 2005
Posts: 12929
    
    3

Embla Tingeling wrote:Maybe it is to discourage the use of primitives in general Java usage, I don't know.

Why would Sun or anyone else discourage the use of primitives in general Java usage?


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32704
    
    4
Embla Tingeling wrote:You're presenting a specific implementation and then immediately discard it as unsuccessful.
You are right; I was mistaken in writing collection rather than Collection.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 16483
    
    2

It's usually fruitless to speculate about why Sun did or didn't do something 14 years ago. But nevertheless I will speculate: once you have described a collection of Objects, you're finished. That collection can contain all types of objects. But there's no type which can represent all primitives, so you'd have to duplicate the code for collections of bytes, of ints, of chars, and so on. Duplicate code... it's a maintenance headache.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32704
    
    4
Paul Clapham wrote:It's usually fruitless to speculate about why . . . did or didn't do something 14 years ago. . . .
Since I last posted, I have thought exactly the same. How can we second-guess what somebody else did 14 years (or 10 years) ago? You are spot on, Paul C.
Raghavan Muthu
Ranch Hand

Joined: Apr 20, 2006
Posts: 3327

Campbell Ritchie wrote:And remember that in the first versions of Java there were few classes, probably only Hashtable Vector and Stack available. Remember all those classes hide their implementation, but are based on arrays.



A good insight CR Thanks!


Everything has got its own deadline including one's EGO!
[CodeBarn] [Java Concepts-easily] [Corey's articles] [SCJP-SUN] [Servlet Examples] [Java Beginners FAQ] [Sun-Java Tutorials] [Java Coding Guidelines]
Monu Tripathi
Rancher

Joined: Oct 12, 2008
Posts: 1365

It's usually fruitless to speculate about why Sun did or didn't do something 14 years ago.

Perhaps it is; I do this in my spare time, usually ;) [sidebar: sigh! what a life?!]

Besides, sometimes you could be asked these questions..you know..like in a job interview/viva voce. People have doubts, they try to find answers and when they dont, they throw these questions at you (at job interviews or oral exams) just to see what you think.

I think I found atleast one good reason/answer for the question, I asked.

nany thanks to all..cheers!
Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4422
    
    2

Jesper Young wrote:Why would Sun or anyone else discourage the use of primitives in general Java usage?

You would have to consult the ancient history books to know why. But as others have said, its pointless now.

I ask rather, why are we still cursed with primitive types in Java today? Sure, in ancient times, it was to sucker C programmers into seeing that Java was better. Or perhaps to sucker C++ programmers. Back then, a lot of people thought that the "everything is an object" meant "this language is dead slow" which has not been true this century.

I think, IMHO and all that, that Java would be better and a lot easier to learn if there were no C-style primatives. Maybe Java++ will get rid of them.
Fred Hamilton
Ranch Hand

Joined: May 13, 2009
Posts: 679
Pat Farrell wrote:

...Back then, a lot of people thought that the "everything is an object" meant "this language is dead slow" which has not been true this century...



unless maybe you are doing recursion.
Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4422
    
    2

Fred Hamilton wrote:
Pat Farrell wrote:"everything is an object"
unless maybe you are doing recursion.


Are you trying to say that using recursion with "everything is an object" is slower than using recursion with primative int/float/char/etc? Because I don't see any evidence of that. Recursive algorithms are known to not optimize as well as loop based implementations, but I don't see that having anything to do with the existance of primitive data types, in either the last or this century.

recursion is very handy and elegant. Its been known for 50 years to not be the fastest way to solve many problems. Sometimes you care about performance, most of the time, you care about engineering effort.
Fred Hamilton
Ranch Hand

Joined: May 13, 2009
Posts: 679
Pat Farrell wrote:
Fred Hamilton wrote:
Pat Farrell wrote:"everything is an object"
unless maybe you are doing recursion.


Are you trying to say that using recursion with "everything is an object" is slower than using recursion with primative int/float/char/etc? Because I don't see any evidence of that. Recursive algorithms are known to not optimize as well as loop based implementations, but I don't see that having anything to do with the existance of primitive data types, in either the last or this century.

recursion is very handy and elegant. Its been known for 50 years to not be the fastest way to solve many problems. Sometimes you care about performance, most of the time, you care about engineering effort.



Yes, there is plenty of evidence that some types of recursion, such as mini-max tree search, are much slower when you "objectify". Try doing a minimax tree search using a loop based implementation and I think you will run into problems.
Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4422
    
    2

Fred Hamilton wrote:Yes, there is plenty of evidence that some types of recursion, such as mini-max tree search, are much slower when you "objectify". Try doing a minimax tree search using a loop based implementation and I think you will run into problems.


You didn't address my question. I'm not talking about whether loop-based replacements for recursion are good or bad.

I'm asking if there are really cases ( in common usage) where using Integer instead of int is critically important to performance. It used to be true. I've not seen evidence of it with modern hotspot and just in time optimizations. I claim that unless there is a huge difference in commonly used models, then the added complexity to the language and learning of having primitive types is no longer justified.
Fred Hamilton
Ranch Hand

Joined: May 13, 2009
Posts: 679
Pat Farrell wrote:
Fred Hamilton wrote:Yes, there is plenty of evidence that some types of recursion, such as mini-max tree search, are much slower when you "objectify". Try doing a minimax tree search using a loop based implementation and I think you will run into problems.


You didn't address my question. I'm not talking about whether loop-based replacements for recursion are good or bad.

I'm asking if there are really cases ( in common usage) where using Integer instead of int is critically important to performance. It used to be true. I've not seen evidence of it with modern hotspot and just in time optimizations. I claim that unless there is a huge difference in commonly used models, then the added complexity to the language and learning of having primitive types is no longer justified.


you said

Recursive algorithms are known to not optimize as well as loop based implementations.


WHich in some cases is most definitely not true.

Depends what you mean by "common usage". I am not talking about common usage. I am saying that there are some situations where using ints instead of Integers makes a significant difference. You can use the example of a minimax tree search in a tree with a large branching factor. It's common in strategy games such as chess. It's a hobby and I've tried it many different ways. I do mine using static arrays, and yes the difference is significant. In general you might be right, but there are situations where it matters. That's about all I can say. If you don't agree well then we'll have to disagree.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 16483
    
    2

Monu Tripathi wrote:
It's usually fruitless to speculate about why Sun did or didn't do something 14 years ago.

Perhaps it is; I do this in my spare time, usually ;) [sidebar: sigh! what a life?!]

Besides, sometimes you could be asked these questions..you know..like in a job interview/viva voce.


I could understand somebody asking "Why would it be a good or bad idea to do X?" in an interview. But if somebody asked me "Why did Sun do X?" I would answer straight out "Since they didn't document their design decisions, we have no way of knowing."
Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4422
    
    2

Fred Hamilton wrote:Depends what you mean by "common usage". I am not talking about common usage. I am saying that there are some situations where using ints instead of Integers makes a significant difference. You can use the example of a minimax tree search in a tree with a large branching factor. It's common in strategy games such as chess. It's a hobby and I've tried it many different ways. I do mine using static arrays, and yes the difference is significant. In general you might be right, but there are situations where it matters.


All generalizations are false, including this one.
Fred Hamilton
Ranch Hand

Joined: May 13, 2009
Posts: 679
Pat Farrell wrote:
Fred Hamilton wrote:Depends what you mean by "common usage". I am not talking about common usage. I am saying that there are some situations where using ints instead of Integers makes a significant difference. You can use the example of a minimax tree search in a tree with a large branching factor. It's common in strategy games such as chess. It's a hobby and I've tried it many different ways. I do mine using static arrays, and yes the difference is significant. In general you might be right, but there are situations where it matters.


All generalizations are false, including this one.


Oh? You are the one who is generalizing. I'm just saying there are situations where using an array of primitives is a better choice. Where I come from that's not a generalization. But if you wanna say that it is, well I can't be bothered to argue.

You know, i knew before I started that I'd probably end up wishing I hadn't joined this thread. Ok dude, you wanna be right here, go ahead. wrap your primitives and use a collection if it makes your life easier. I'm bowing out of this waste of time.
Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4422
    
    2

Fred Hamilton wrote:Oh? You are the one who is generalizing..... I'm bowing out of this waste of time.


Whatever Fred. You don't seem to be reading very will today. I make a generalization that is generally true, you refute it with a special case. I say, yes, there are always special cases that don't meet the general truth, you complain, I point out that all generalizations are false on occasion. Dude, I'm 99% agreeing with you. Don't get all huffy.
salvin francis
Ranch Hand

Joined: Jan 12, 2009
Posts: 915

keep it cool guys
Its just a Collection of guys here trying to solve an array of difficulties posted by fellow programmers


My Website: [Salvin.in] Cool your mind:[Salvin.in/painting] My Sally:[Salvin.in/sally]
salvin francis
Ranch Hand

Joined: Jan 12, 2009
Posts: 915

on second thought,

what would be more optimised ?


vs:


btw, i do believe that we need primitives, just my own opinion that i would be glad to justify
Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4422
    
    2

Well, do you need to change the collection? or can you use Google Collection's ImmutableList?
Its much faster than the general List, and thread safe and other good things.

List<Integer> myList = ImmutableList.of(10, 20, 25,40);

Or even better

ImmutableList<Integer> myList = ImmutableList.of(10, 20, 25,40);

Actually, the two are the same for speed, but the second tells the user that its an ImmutableList and they should know that they can not expect things like


myList.add(42);

to work
salvin francis
Ranch Hand

Joined: Jan 12, 2009
Posts: 915

thanks on the ImmutableList info, i would definately look into that,

but i guess (not sure) in my example posted, the primitive version would be faster
Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4422
    
    2

I'm not sure your primative example will even compile.

If it was

int[] myBasicPrimitiveArray = new int {10,20,30};

then I would expect it to compile, and yes, for three dinky values it would be faster than an ArrayList. But you are comparing apples to oranges.

I would expect no useful performance change between

Integer[] objarray = {10,20,30);
and
int[] primarray = {10,20,30);

This is a classic premature optimization.
salvin francis
Ranch Hand

Joined: Jan 12, 2009
Posts: 915

sorry for the typo,


hmm I am a bit cynical about


Vs
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32704
    
    4
Don't understand why you are cynical about that, SF.
salvin francis
Ranch Hand

Joined: Jan 12, 2009
Posts: 915

i dont knw, but just a gut feeling that


is more memory efficient than:



its just a feeling, i may be wrong.
Personally i dont prefer to use wrappers until there is a strong reason for it.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32704
    
    4
Agree, you usually get better performance with primitives, and you would save a little memory with the int[] array.
Somnath Mallick
Ranch Hand

Joined: Mar 04, 2009
Posts: 471
Not to mention primitives are easier to handle! May be that's why they are called Primitives!
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32704
    
    4
Maybe that's why they are called primitives, but a more likely reason is that the actual value of the number is stored in memory, rather than its location.

Also primitives have no methods associated with them; objects do.
Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4422
    
    2

Campbell Ritchie wrote:you usually get better performance with primitives, and you would save a little memory with the int[] array.

Is it not more that you used to usually get a little better performance and memory usage with int[] but every release of the JVM has better optimizations, JIT compilations and other tricks so that for most actual uses, they are asymptotically equal.

Back in 96, sure, there was a big difference, and even I saw the value in them. Today, not so much.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32704
    
    4
Good point, Pat, particularly when you consider that C# has managed to blur the distinction between primitives and objects. It's by no means new; languages like Eiffel were doing it a ΒΌ century ago.
salvin francis
Ranch Hand

Joined: Jan 12, 2009
Posts: 915

Pat, i do admire the details you have provided over the primitives vs Objects discussion,
but, to be honest I prefer primitives over objects,
sometimes optimization plays a major role in things,

for eg:
imagine handling a database query fetching a 1000 objects from db each having 5-10 primitives, I would not even think of using wrappers here,
though the memory imprint difference would be small for a primitive, when it comes to real industry coding with scenarios such as
reducing the server's session object's memory imprint (Man that's tough) the little things do matter...
Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4422
    
    2

salvin francis wrote:I prefer primitives over objects, sometimes optimization plays a major role in things,

imagine handling a database query fetching a 1000 objects from db each having 5-10 primitives


You are entitled to your opinion, even when its completely wrong :-)

Seriously, in a JDBC retrieval of ten fields from a record, even done 1000 times, there is no important difference between retrieving an Integer over an int. And no impact of the conversion itself.

I would not consider your case even performance sensitive, 1000 records being fetched is completely dominated by the delay between application and the DBMS server over the network, you can do tons of things and no see any impact. Perhaps you have benchmarks that show that fetching 1000 records is a big deal, but I've not seen that be the case, its fetching 1000 records for 500 users that becomes an issue, and again, the Java/JDBC performance is rarely the bottleneck. Its always the DBMS engine or the network or things related to that.
salvin francis
Ranch Hand

Joined: Jan 12, 2009
Posts: 915

salvin francis wrote:imagine handling a database query fetching a 1000 objects(not records) from db each having 5-10 primitives, I would not even think of using wrappers here

maybe you misunderstood me, I meant objects not records, eg: fetch all Persons from database whose age > 20.
so, you would query DB, get details: name, age, etc, create a Person Object, and populate it.

I do not wish to debate over who is right and wrong
we are all here to help each other...
Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4422
    
    2

salvin francis wrote:maybe you misunderstood me, I meant objects not records, eg: fetch all Persons from database whose age > 20.
so, you would query DB, get details: name, age, etc, create a Person Object, and populate it..

Clearly I did. Your Person object has fields, perhaps Name, Birthdate, Gender, etc. I'm saying that for those contained fields, it makes zero difference if they are primitive or Objects.

Of course its a ton more pleasant to work with a List<Person> than a two dimentional Object[][]
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Why do Collections(save Arrays) allow only Objects?
 
Similar Threads
XDoclet ==> Continuous Integration
interface is abstract?
regarding ServletContextListner
Avatar support?
Ronald Reagan dead at 93