Click to See Complete Forum and Search --> : java arrays


TheLinuxDuck
06-07-2001, 04:32 PM
Well, in my quest to familiarize myself with java, I decided to examine arrays, namely string arrays (for this example). Let me post the code first, and then I'll ramble/question:

import java.io.*;
import java.util.*;
//
public class StringTest1 {
public static void main(String[] args) {
String[] stringArray=new String[10];
//
stringArray[0]=new String("Crap");
Arrays.fill((String[])stringArray,1,2,(String)"Sniffer");
stringArray[2]="Blork blork";
//
for(int j=0;j<stringArray.length;++j) {
if(stringArray[j]!=null)
System.out.println(j + ": " + stringArray[j]);
}
}
}


As you can see, I used three different methods for assigning data to three different slices of the array.
--1. The first creates new string space to assign data. Is this the best way? Why?
--2. The second uses the fill method of java.util.Arrays, typecasting the array and the fill item. Does this way offer any benefits, or is it merely a long way to the same end of different means?
--3. Direct assignment to a slice. Does this do basically the same thing as #1, or are there subtleties to what gets done?

What are some other methods for creating arrays? I'm aware of List, Vector, and ArrayList, but I don't know much about their benefits. Can someone tell me a little about why each of these would be used?

A simpler explanation would be fine, cuz I know I'm asking for a lot of shizz in this thread... (^=

Thanks!!!!!!!!!!

Dru Lee Parsec
06-07-2001, 06:04 PM
1 and 3 are essentially the same. I'll have to look into wheather those two methods do something funky with memory behind the scenes.

Guess what? I've never seen #2 before. Duck, You just taught ME something about Java!

I always tend to use Vector, ArrayList, or Hashtable for my collections so I rarely work with arrays. The reason for this is that a collection like Vector can contain anything derived from java.lang.Object. So it can't hold primitive data types like int, float, boolean and so on (Hence the need for Integer, Float, and Boolean classes).

The same thing goes for arrays. An array is not an object therefor you can't, for example, have a Vector of arrays. But you could have a vector of vectors, or an ArrayList of ArrayList's (or Vectors, or Hashtables or whatever).

Arrays.fill I like that! ;)

TheLinuxDuck
06-08-2001, 12:14 AM
Originally posted by Dru Lee Parsec:
<STRONG>Guess what? I've never seen #2 before. Duck, You just taught ME something about Java!</STRONG>

Qool! I'm always glad to help, even though it was pure happenstance.. (^=

<STRONG>The reason for this is that a collection like Vector can contain anything derived from java.lang.Object. The same thing goes for arrays. An array is not an object.</STRONG>

?? Do you mean an Object class? According to this reference (http://www.java.sun.com/j2se/1.3/docs/api/java/lang/reflect/Array.html), an Array is extended from an Object.

<STRONG>therefore you can't, for example, have a Vector of arrays.</STRONG>

The Vector class's (http://www.java.sun.com/j2se/1.3/docs/api/java/util/Vector.html) addElement function accepts an Object, of which an array can be cast. Here is a modified version of the previous code to create two string arrays, dump them both into a vector, then retrieve one and print it out.


import java.io.*;
import java.util.*;
//
public class VectorArray1 {
public static void main(String[] args) {
String[] stringArray=new String[4];
String[] stringOther=new String[2];
//
stringArray[0]=new String("Crap");
Arrays.fill((String[])stringArray,1,2,(String)"Sniffer");
stringArray[2]="Blork blork";
stringOther[0]="Second array, first spot";
stringOther[1]="Second array, second spot";
//
Vector myVector=new Vector();
//
System.out.println("Vector has " + myVector.size() + " items.");
myVector.addElement((String[])stringArray);
myVector.addElement((String[])stringOther);
System.out.println("Vector has " + myVector.size() + " items.");
//
String[] string2;
string2=(String[])myVector.firstElement();
//
for(int j=0;j&lt;string2.length;++j) {
if(string2[j]!=null)
System.out.println(j + ": " + string2[j]);
}
}
}


<STRONG>Arrays.fill I like that! ;)</STRONG>

(^=

kmj
06-08-2001, 08:56 AM
I think the confusion here is that (and Dru will surely correct me if I'm wrong) Java supports somewhat 'native' arrays and an Array class; same with integers. There's an Integer class, but also there's the primitive data type 'int'. Wheny you do String bob[8], you're creating an array of 8 strings, but you're not using the Array class.

TheLinuxDuck
06-08-2001, 09:13 AM
Originally posted by kmj:
<STRONG>I think the confusion here is that Java supports somewhat 'native' arrays and an Array class; When you do String bob[8], you're creating an array of 8 strings, but you're not using the Array class.</STRONG>

If that is the case, it shouldn't change anything, because the Array class is still derived from the Object class, which can be typecast to be used in a Vector class. I'm not familiar with the Array class, but will check it out ,yo.

See, I'm a troublemaker. I make trouble. Trouble is my name, trouble is my game, I eat sleep breath and shh.. and poop trouble.

Just call me 'Hey! Troublemaker!' then ask me 'You making trouble?'.

TheLinuxDuck
06-08-2001, 09:34 AM
Ok, so the Array class only provides static methods, which means that I can't create an object of type Array.

And since I learned this all by myself without any help from kmj in AIM or anything.. (^=

Ok... well, the confusion has been lifted, the fog cleared, the smoke dissipated, the noise quietened, the haze ventilated...

YES KMJ HELPED ME! I AM A LOSER! (^=

kmj
06-08-2001, 09:38 AM
disclaimer: I don't what I'm talking about and anything I say may or may not be correct.

TheLinuxDuck
06-08-2001, 09:43 AM
The point this is to learn, and to become familiar with the language. Since I'm not that familiar, I am challenging you, Dru, and myself so that I will find the boundaries and define them, so that my future work with java will be based on not only 'question' experience, but also 'do' experience.

So, maybe I said something stupid. Or maybe I did something that was stupid. Or maybe not.

This whole speech can be applied to you as well (kinda like a bandaid). Consider the lillies..

Dru Lee Parsec
06-08-2001, 11:59 AM
Consider the Lilies!? He's making it up as he goes along!

YOu guys are both right. The Array class is derived from Object, but an "array" (notice the lack of capitalization) is this:

int[5] myArrayOfInts

BTW, Learning by "doing" is the best possible way to learn Java, or any other language. You really don't grok a programming language until you get it under your fingers.

TheLinuxDuck
06-08-2001, 02:05 PM
I am learning alot by questioning and trying.. I keep picking at the code until it compiles and runs.. the java docs have become my best friend now.. (^=

I think I should go through 'thinking in java' from beginning to end though, to pick up on stuff I normally would have missed.

However, I'm slowly becoming enthralled with java! (^=

In fact, if it keeps going like it is, I may have a real live project to do with it!

kmj
06-08-2001, 02:27 PM
how's that saying go? You can pick your code, and you can pick your friend's code, but you can't pick your scabs and eat them unless you're trapped on a desert isle?

TheLinuxDuck
06-08-2001, 02:41 PM
Uh... that wasn't in the form of a question?

Dru Lee Parsec
06-08-2001, 04:47 PM
KMJ:

Eeww! Yech!
Go sit in the corner and take a ten minute time out for that one.

:(

[ 08 June 2001: Message edited by: Dru Lee Parsec ]

kmj
06-08-2001, 05:33 PM
Dru: word, yo. I hate looking at other people's code. :D

nanode
06-11-2001, 01:47 PM
For general purpose collections, I also use Arraylists and/or Vectors. However in a case where all elements are guaranteed to be of a certain type (or class) simple arrays do fine.

Why bother casting an object back to it's original form if you can avoid it?

TheLinuxDuck
06-11-2001, 02:24 PM
Originally posted by nanode:
<STRONG>For general purpose collections, I also use Arraylists and/or Vectors. However in a case where all elements are guaranteed to be of a certain type (or class) simple arrays do fine. </STRONG>

If you've got a Vector, and it contains items of different types, how do you determine what type of object it is?

[edit]

Er.. I mean what type of objects are being read from the Vector.. (^=

[ 11 June 2001: Message edited by: TheLinuxDuck ]

Dru Lee Parsec
06-11-2001, 03:12 PM
If you've got a Vector, and it contains items of different types, how do you determine what type of object it is?


You can use Run Time Type Identification (RTTI) and the Java Reflection package. Here's a good link for that: http://java.sun.com/docs/books/tutorial/reflect/index.html

But the vast majority of the time your collections are either:

A collection of the same types of objects
Or, a list of objects all derived from the same base class.

[ 11 June 2001: Message edited by: Dru Lee Parsec ]

kmj
06-12-2001, 08:01 AM
or same interface (?)

nanode
06-12-2001, 10:46 AM
A class implementing an interface works just the same as inheriting from a super - as far as casting goes. Keep in mind, if you cast something as an interface which it implements, then you can only do what that interface can do.

There's more than one way to do it, just use the best tool for your task.

TheLinuxDuck
06-12-2001, 11:58 AM
Originally posted by nanode:
<STRONG>just the same as inheriting from a super</STRONG>

Newbie question:

What do you mean by this? Do you mean creating a class:

public class Coordinate {
public int x,y;
}

and then extending it with another class:

public class Coordinate3D extends Coordinate {
public int z;
}

???

Is that what 'inheriting from a super' entails?

<STRONG>Keep in mind, if you cast something as an interface which it implements, then you can only do what that interface can do. </STRONG>

I'm cornfused as to what an interface really entails. Can you explain, and possibly offer an example?

&lt;--- (pesky newbie)

nanode
06-12-2001, 01:42 PM
TLD:

You're right on about extending the class.

Interfaces are pretty simple:

public interface LameInterface {

public void doGreet();
public void doInsult();
}


Then you can implement the interface"

public class LameClass extends SomeOtherClass implements LameInterface {

//constructor
public LameClass() {

}

//member method
public void doLameStuff() {
System.out.println("blahblah");
}

//implement methods defined in LameInterface

public void doGreet() {
System.out.println("Hello");
}

public void doInsult() {
System.out.println("yo mama is ugly");
}

}


If you were to take a several instances of LameClass and put them into a vector (or ArrayList etc.) they are stored as java.lang.Object.


//snippet...
LameClass lc = new LameClass();
Vector v = new Vector();
v.add(lc);

//...

LameInterface y = (LameInterface)v.get(0);


the y variable only has the methods from the LameInterface available. Even though LameClass has doLameStuff() we can't use it, since we casted as the interface.

This might seem really complex and silly, but there are times when this can be very powerful. Interfaces allow many different classes to a share a common set of methods. Each class can implement those methods differently, but the interface is consistent.

Hope that didn't hurt too much. :)

TheLinuxDuck
06-12-2001, 02:20 PM
So, then, you could create a common set of functions that apply to a set of different classes, and after placing items into a vector, you could technically call these functions without regard to what type of object is in the vector, as long as you know that each type in the vector implements the interface.

I suppose it makes sense.. I also suppose that won't really get it until I'm in a situation where I need to use it practically.

Hmm...

Dru Lee Parsec
06-12-2001, 02:30 PM
So, then, you could create a common set of functions that apply to a set of different classes, and after placing items into a vector, you could technically call these functions without regard to what type of object is in the vector, as long as you know that each type in the vector implements the interface.


BINGO!
That's it exactly!. If you are familier with C++ then think of a Java Interface as a pure abstract class. That is, a class that has methods declared, but none of the functionality defined.

So the interface is saying "Anything that implements me MUST have these methods". So you can pass various types of objects to a method that receives (in nanode's example) lameInterface. And as long as you only use the methods in the interface then you can manipulate them regardless of what the actual classes are. This is very strong use of polymorphism. In fact, it's almost the definition of polymorphism.

Thought example. You have a bunch of reports that have completly different outputs, graphics, data, etc. But they all implement an interface you wrote called "Printable" that has one method called printMe().

You select a group of reports and pass that collection of reports to a method that walks through your collection and calls the printMe() method on each of them. So, even though each report object has a completly different set of code to make each of them print correctly you can pass a collection of objects of COMPLETLY DIFFERENT TYPES to the same method. As long as they all implement the Printable interface.

Isn't that cool!