Newbie Java array question

Status
Not open for further replies.

Bagheera

Ars Tribunus Angusticlavius
8,773
Subscriptor
I'm a CS student taking a 100-level class in Java. We're just learning about Java arrays this week. I posted this in the class conference, and I'd like to get some input from experienced programmers on Ars.

-----------------------------------------------------------------------------------------------------

I can't help but focus on the fact that Java arrays can't be dynamically resized. The "deep copy" method described in our book* seems entirely too complicated.

The only other programming language I know is Powershell. I'm told it handles arrays in a manner that similar to Python and other common scripting languages. In Powershell, arrays can be increased in size as you add more elements.

Say, for example, that you have an array of e-mail addresses. You could initialize an array with:
$EmailAddresses=("user0@mycompany.com","user1@mycompany.com","user2@mycompany.com")
Now we have an array with 3 elements. But what happens if we want to add more elements and increase the size of the array? Do we need a deep copy? Do we even have to worry about the array's memory allocation? No, we just enter the next elements:
$EmailAddresses=$EmailAddresses+user3@mycompany.com"

$EmailAddresses=$EmailAddresses+"user4@mycompany.com"

$EmailAddresses=$EmailAddresses+"user5@mycompany.com"
Now we have an array with 6 elements. In Java, we would need to do a deep copy for each of these three lines. If we're pulling thousands of e-mail addresses from a database, and we don't know exactly how many addresses there are, we have to set up a deep copy loop for every single address we add.

I imagine Powershell (and other languages) performs something like a deep copy when we add an element; we just don't have to explicitly program it every time. I'm certainly not saying Powershell is superior to Java. It just seems that Powershell makes arrays easier to handle. Can someone with more programming experience comment on this?

--------------------------------------------------------------------------

* The "Deep Copy" method was written as:

public static int[] deepCopy(int[] array1) {
int[] array2 = new int[array1.length];
for (int i = 0; i < array1.length; i++) {
array2 = array1;
} // end for

return array2;
} // end method


 

Blacken00100

Ars Legatus Legionis
10,130
Subscriptor
Unless you know the exact size of your working set, you shouldn't use arrays at all. This is that ArrayList<T> is for. Java arrays conform to the traditional "array" concept (in interface and generally in implementation); they are of static size. Most frequently, languages with "dynamic arrays" don't have arrays at all, but other constructs "helpfully" mislabeled as arrays. PowerShell is one of these.

Be careful of assuming anything based on a shell scripting language. Also, your book sounds like a piece of shit; I'd go Thinking in Java or something (it's freely available online).

(Aside: you may find yourself pissing people off if you write statements like your quoted bit. You can get away with that tone when you know half a dozen languages well enough to write production code, but before then it sounds "precocious," and "precocious" is just a fancy word for "douchey." Understand that your classmates, if not you yourself, cannot be relied upon to possess the fundamentals necessary for your instructor to provide a meaningful answer. Smells show-offy.)
 

Faramir

Ars Legatus Legionis
36,356
Subscriptor
Java is no longer a young language and there is a lot of legacy code out there. I think if the designers had their druthers native arrays would have been deprecated in favor of the collection classes (I bet they'd like to get rid of all primitives). But in the early going when they were trying to attract programers to this new language having a native array class was necessary for people coming over from C++ (at the time STL was not in widespread use).

In any event any sort of collection implementation is going to have trade-offs. Some are optimized for lookups, some for sorting, some for adding and subtracting elements ect. Take a look at the chart on this page: http://www.coderfriendly.com/2009/05/12 ... heatsheet/ for a good overview.
 

Blacken00100

Ars Legatus Legionis
10,130
Subscriptor
I don't know if I'd go that far. The array construct is a valuable one, and isn't really a "primitive" at all (it is a hilariously horrible hack but it isn't a primitive).

If you need to resize an array in the normal course of programming, however, that should be something of a warning flags. Most shitty Java books come from programmers who are C++ programmers first and Java programmers second, which is why stuff like "deep copying arrays" is covered at all.
 

Bagheera

Ars Tribunus Angusticlavius
8,773
Subscriptor
Blacken00100":4f3t4v79 said:
If you need to resize an array in the normal course of programming, however, that should be something of a warning flags.

Really? What if you're querying multiple tables in a database, or grabbing event logs from multiple servers, or grabbing looped input from a user? In each case, you don't know how many elements (how many rows, events, or inputted items) you'll eventually get. Is that a warning sign or just typical programming?
 
Bagheera":1rn07d2d said:
Really? What if you're querying multiple tables in a database, or grabbing event logs from multiple servers, or grabbing looped input from a user? In each case, you don't know how many elements (how many rows, events, or inputted items) you'll eventually get. Is that a warning sign or just typical programming?

err it means, dont use a fixed sized array, use a list instead or something similar.
 

Blacken00100

Ars Legatus Legionis
10,130
Subscriptor
Faramir":2ci3jkgv said:
The point is that in those situations you shouldn't be using an array. Rather you probably want some kind of list.

Edit: beaten

Re: primitives
I guess the syntactic sugar made it look primitive. I had no idea it was implemented in such a hacky manner.
Dude, Java in general is that way. It is seriously amazing that it works as well as it does. The guy in the next cube over is a former JVM hacker (has a JSR still pending for Java 7) and the only time I've ever seen this hippie-ish dude get mad is talking about the code in javac.
 

jbode

Ars Legatus Legionis
11,752
Subscriptor
Bagheera":9o11apv8 said:
Blacken00100":9o11apv8 said:
If you need to resize an array in the normal course of programming, however, that should be something of a warning flags.

Really? What if you're querying multiple tables in a database, or grabbing event logs from multiple servers, or grabbing looped input from a user? In each case, you don't know how many elements (how many rows, events, or inputted items) you'll eventually get. Is that a warning sign or just typical programming?

You don't use arrays for those situations; you use some sort of collection type that can be dynamically sized, such as a Vector or a List in Java.
 

Blacken00100

Ars Legatus Legionis
10,130
Subscriptor
Bagheera":qbk6l9xm said:
Blacken00100":qbk6l9xm said:
If you need to resize an array in the normal course of programming, however, that should be something of a warning flags.

Really? What if you're querying multiple tables in a database, or grabbing event logs from multiple servers, or grabbing looped input from a user? In each case, you don't know how many elements (how many rows, events, or inputted items) you'll eventually get. Is that a warning sign or just typical programming?
Yes. Really. (You would have done better to pick up on my mention of ArrayList<T> and investigate Java containers instead of getting snippy.)
 
Blacken00100":2loxcnir said:
The array construct is a valuable one,
Yes, in that it allows ArrayList to be implemented in terms of it. It's rare that you need to use arrays (directly). You should virtually always use collection classes. (Unfortunately, for non-blocking atomic operations on list elements, you sometimes have to use Atomic*Array classes, which thinly wrap arrays' shitty API.)

and isn't really a "primitive" at all
Except that you can't implement it from scratch in Java code, so in that sense it's primitive. Conceptually, it's primitive because it's low-level.
 

Blacken00100

Ars Legatus Legionis
10,130
Subscriptor
newwb":1lipscrs said:
Blacken00100":1lipscrs said:
The array construct is a valuable one,
Yes, in that it allows ArrayList to be implemented in terms of it. It's rare that you need to use arrays (directly). You should virtually always use collection classes.
Sure - at least, for most developers. (It's why I mentioned ArrayList in the first place.)

and isn't really a "primitive" at all
Except that you can't implement it from scratch in Java code, so in that sense it's primitive. Conceptually, it's primitive because it's low-level.
"primitive" in that sense is really squishy, though. I mean, "int" is a primitive. Literally. Arrays, not so much. But that's just semantics.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
note that, thanks to java's hilariously screwed up generics implementation you may find yourself needing to use either arrays or someone else's well implemented special cased list/map/whatever for each primitive even at the cost of awful code bloat) since the boxing/unboxing may be a problem.

Obviously that would be premature optimisation unless you actually already know it's a problem (if you do any scientific computing there's a very good chance it would be)

The above is likely well past the OP's current level but come back to it in a few months and see if you understand it then.

Be very careful about talking about deep copy operations and the implications of it until you understand the difference between types with copy semantics (in java primitives) and types with reference semantics (implying a concept of identity), also understand why immutability means you can stop worrying about it (and hence why you can treat strings as if they were either in most cases)
 

Afty

Ars Scholae Palatinae
1,434
Two comments here:

1) How is that "deep copy" code sample a deep copy? When I think of deep copying, I think of taking an array of references and allocating a copy of each element and storying that in the new array. You would recursively do this for each non-primitive field in each object in the array as well. In this case, it's just a normal array copy. I'm not sure why they called it a deep copy.

2) In your example, you're increasing the size of the array by 1 each time, so you do have to copy the array each time you add an element to it. In reality you would increase the size of the array by a larger amount so you wouldn't have to copy it with each insertion. This is what ArrayList does under the covers, as do other dynamically sized array implementations. A typical strategy is to double the size of the array each time you have to resize it.
 

pyu

Ars Praefectus
5,108
Subscriptor
You can use the System.arraycopy method if you want. But as others have mentioned, why bother? Just use a class from the Collections package which supports resizing when it hits some predefined resizing threshold. :)

Once u know that in and out and realize the pitfalls of the JVM and Java itself, you might want to give Google's version of Collections a try or pick up a functional programming language or two.
 

Blacken00100

Ars Legatus Legionis
10,130
Subscriptor
vafarmboy":1w403565 said:
Relax, kids. He's in an intro class. He's got to learn what an array is and its limitations are before he can blithely use all the happy fun collection stuff that makes them not totally suck to use. I mean, who wouldn't teach manually managed memory in a language where you're not supposed to have to manage memory manually?
Eh - you're not "manually managing memory," at least not in the sense his instructor is (probably) driving toward. An array is, IMO, a very conceptually simple data structure, and starting there isn't the worst thing in the world.

(His making himself look like a bit of a douche by assuming things based on information he does not possess is probably more concerning. Not too awesome for someone in an intro class.)
 

forquare

Seniorius Lurkius
37
I often use arrays if I know how many elements I'm likely to need before I compile the program. It doesn't happen often, but it can sometimes be helpful.

While ArrayList<E> is a good choice, if you ever start playing about with threads then you should consider using Vector<E> as it is thread safe. I hear that there is something of a performance hit when using a Vector, but it isn't much. Thus, it depends on what you are doing as to whether you'll want to use it or not.
 
If you're using multiple threads to store elements in a single list, chances are that accessing the list in a thread-safe manner doesn't buy you much as usually you want thread safety in a coarser-grained manner. For example, if you call hasNext() on an iterator, you may want to be sure that the list still has a next element when you subsequently call next(), or if you see that the list is not empty and then remove the first element, you want to know that another thread didn't just remove the first element.
 
Right. It can be replaced by array1.clone(). The only point of doing this is so that you can modify one array independently of the other - not so that you can store more things in an array. To resize, you'd have to do something like:
Code:
static int[] resize(int[] orig, int newLength) {
  int[] neww = new int[newLength];
  System.arraycopy(orig, 0, neww, 0, Math.min(orig.length, newLength));
  return neww;
}
Basically, you create a new array and copy elements over from the old array to the new array.
 
Status
Not open for further replies.