Why isn't .length() a method for arrays in Java? [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java - Array’s length property
String.length() vs Array.length
I'm currently in my AP Computer Science class in high school and I came across this in my reading.
From what I understand, .length() is a method used for strings, but why isn't .length() a method when applied on arrays? I understand that they're different objects, but why didn't Java just make another method for finding the length of arrays?
I appreciate any response I get. Thanks!

Since arrays are fixed length defined at the time they are instantiated length is a public final field on the class. There is no need to make it a method since there is no calculation to be done at run time.
See this section of the Java Spec for details:
http://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html#jls-10.7
Now, as for the design question of why they didn't provide an accessor method to obtain the value isn't specified. Perhaps this was done before any other convention was set and this is just a legacy thing. Only the language designers would know the "why" portion of their decision to do it this way.

Arrays are defined in the Java Language Specification #10.7. In particular:
The members of an array type are all of the following:
The public final field length, which contains the number of components of the array. length may be positive or zero.
[...]
I can't answer why this approach was chosen by the language designers.
Interestingly, it was already the case in the Oak specifications, which is the ancestor of Java.

I doubt that there's a good technical reason for this.
I suspect that this is one of those little inconsistencies that didn't get spotted early enough to get fixed without breaking a ton of code.

Related

Why is `Set.of()` implemented differently from `Collections.emptySet()`? [duplicate]

This question already has an answer here:
Map.of() vs. Collections.emptyMap()
(1 answer)
Closed 1 year ago.
As far as I can see, the contracts of both are identical. Seems rather pointless to implement a whole new empty set for Set.of().
I would presume the standard library implementors are aware of Collections.emptySet(), so there must be a specific reason I am not seeing. Due to the very generic method names, searching in mailing lists is impossible, so I am not sure if this was discussed.
(BTW, it seems Set.of() just uses a SetN with an empty input array, so it will probably be less efficient than emptySet() as well.)
There is a single difference "code-wise", that I am aware of.
Collections.emptySet().contains(null); // false
Set.of().contains(null); // NullPointerException
So they are not inter-changeable.
Set.of() uses a nice clean helper from ImmutableCollections which was introduced with Java 9.
Collections on the other hand was says since 1.2, and was only "adapted" to generics and such things over time.
So:
the Collections implementation is historically grown, and you would probably not be doing it like that any more today
so, when introducing the functionality in a new context, you do it in a different way.
And more importantly: all the of methods within Set are just delegating to ImmutableCollections. And then it makes no sense that of() would be implemented in a completely different way than all the other of(x) methods.

Is there anything inherently wrong with long variable/method names in Java? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
When is a Java method name too long?
I know this is probably is a question of personal opinion, but I want to know what's standard practice and what would be frowned upon.
One of my profs in university always seems to make his variable and method names as short as possible (getAmt() instead of getAmount) for instance.
I have no objection to this, but personally, I prefer to have mine a little longer if it adds descriptiveness so the person reading it won't have to check or refer to documentation.
For instance, we made a method that given a list of players, returns the player who scored the most goals. I made the method getPlayerWithMostGoals(), is this wrong? I toiled over choosing a way to make it shorter for awhile, but then I thought "why?". It gets the point across clearly and Eclipse makes it easy to autocomplete it when I type.
I'm just wondering if the short variable names are a piece of the past due to needing everything to be as small as possible to be efficient. Is this still a requirement?
Nothing inherently wrong, it's better to make it descriptive than cryptic. However, it's often code-smell for a method that is trying to do too much or could be refactored
Bad: getActInfPstWeek
OK: getAccountInformationForPastWeek()
Better getAccountInformation(DateRange range)
I prefer to have long variable/method names that describe what's going on. In your case, I think getPlayerWithMostGoals() is appropriate. It bothers me when I see a short variable name like "amt" and I have to transpose that in my head (into "amount").
Something like getAmt() is looks like C++ code style... In java usually are used more descriptive names.
Your professor made a good understandable method. But it's very popular word. It's not a general case. Use your "longWordStyle" style it's more java.
As per standards, longer descriptive names are advised to make it more readable and maintainable on longer term. If you use very short naming e.g. a variable as a, you will forget yourself, what that variable is meant for after sometime. This becomes more problematic in bigger programs. Though I don't see an issue in using getAmt() in place of getAmount(), but definitely getPlayerWithMostGoals() is preferable over something like getPlayer().
Long names, short names, it all depends. There are a lot of approaches and discussions but in fact a method's name should reflect its intention. This helps you to further understand the code. Take this example.
public void print(String s)
Nifty name, short, concise... isn't it? Well, actually no if there's no documentation to tell you what do you mean by "Printing". I say System.our.println is a way of printing a string but you can define printing as saving the string in a file or showing it in a dialog.
public void printInConsole(String s)
Now there are no misunderstandings. Most people can tell you that you can read the method's JavaDoc to understand it but... are you going to read a full paragraph to decide if the method you're going to use does what you need?.
IMO, methods should describe at least an action and an entity (if they're related to one). "Long" is also a perception... but really long names make the code hard to structure. It's a matter of getting the proper balance.
As a rule of thumb, I'd void abreviations and use JavaDoc to further describe a method's intention. Descriptive names can be long but the reward is both readability and a self-explainatory code.

String.length() vs Array.length [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why is String.length() a method?
Java - Array's length property
Was there a specific design/performance reason as to why String has a method for length but Array has a variable length?
There is no Array class in Java (other than in reflections). Arrays are "primitives" of a sort in Java and play by different rules from declared classes.
Certainly a length() method could have been defined on arrays, but the designers wanted to keep length as a property rather than a pseudo-method. (In part this may have made it easier for early Java implementations.) The reasons are somewhat buried in history.
(A better question is why Java couldn't decide whether to call the concept "length", "count", or "size" -- I always end up trying all three before I hit on the right one for an aggregating class.)

"..." being used in Java? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Can I pass an array as arguments to a method with variable arguments in Java?
What is … in a method signature
I first saw this when I was modding Minecraft. It had a constructor that specified (String ... line), and thought it was just some shorthand that Mojang had created. But now, I was looking over ProcessBuider, and saw it again. I was wondering what this is used for. My best guess is that it allows developers to add as many of that type of object as they want. But if that's the case, why not just use an Array or List?
So, really, I am asking two questions:
What is the "..." operator, and
Why would it be more useful than using an Array or List?
... indicates a multiple argument list to a variadic function: a function that can take a variable number of arguments.
For an example of this, look at PrintStream.format. The first (required) argument is a format String, and the remaining 0 or more arguments fulfill that format.
It is called varargs, and as you say it is used to be able to let a method be called with any number of arguments of the specified type. It was introduced in Java 5.
You can read more in the Java tutorials - Varargs.
This is equivalent to a String[] line. It is Java's equivalent to the varargs keyword in C/C++. Similar to C/C++ it must appear as the last parameter.
You've already answered question #1 yourself. As to why it's more useful, it's just a shorthand that requires less typing.
To answer your second question, one advantage of varargs is that you can call a function taking varargs parameter without passing that param. Whereas instead if your function takes in an array, and you need to call it without any value, the caller needs to explicitly pass null.

Is there anyway to determine how big an object is in java? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
sizeof java object
In Java, what is the best way to determine the size of an object?
Hi,
Why is there no sizeof in java? how can one know how big is an object?
thank you
Yes there is. Here is an example of how this can be done. Another way is to declare at object and take the Runtime.freeMemory() both before and after the object has been instantiated than look at the difference.
Use a profiler if you want to know your how much memory your program is using.
Basically, the size of an object is one of those things you don't need to be very aware of in Java. Makes you won't why it is so essential in C/C++. ;)
The longer answer is that you can use Instrumentation.getSizeOf(Object) but its not simple to use.
This is a complex discussion because what do you mean by "size"? Do you mean for instance how many bytes does Java take to represent an int, or a char etc? Or do you mean how many bytes does it use to store the reference to the object? Or how many bytes do the internal structures employed by the JVM use to create and store all the data in that object? I would venture to guess the answers to the last 2 questions is OS-dependent and I don't think you can standardize it. (For instance on 64-bit machines, it's easier for the OS to deal with a 64-bit integer at a time rather than 32 -- so quite likely internally a Java int will be represented on 8 bytes, even though java int's store only 32-bit values.)
There are ways to find out some of these -- for instance look at this: http://devblog.streamy.com/2009/07/24/determine-size-of-java-object-class/ -- but they won't be consistent across OS's.

Categories

Resources