Array class extention
For each array an implicit class will be generated (e.g. "MyClass["). This class extends Object and implements Serializable and Cloneable. I would appreciate to have the possibility to extend this class in order to provide additional methods or at least override methods which are designed to be overriden (e.g. equals). Something like:
class MyClass[] {
// (Re-)Define methods which appear in the array itself and not in each array element.
What do you think about it?
If anything , Arrays should only be collections. Not
lists, because they don't implement the list
interface. Why? Not expandable, list requires that
you have a function add( Object ). In the collection
interface, it's optional.
The more I think about this, the more I think that
it's not a good idea. A better idea would be to wrap
your arrays in another object that implements List.
So you'd have a List that was backed by an array.Not so. From the JDK 1.4 documentation for AbstractList:
void add(int index, Object element)
Inserts the specified element at the specified position in this list (optional operation).
The proposed Array class would implement AbstractList and throw UnsupportedOperationException for the 'optional operations' that involve changing the size of the list. Yes, a fixed-size array can be fully compliant with the contracts of List and AbstractList.
Guys, you misunderstand me. I'm not proposing that Array is a wrapper for a native array. I'm proposing that Array is a native array. In the same way that "hello" is just syntactic sugar for new String("hello"), and similarly a + b with Strings is just syntactic sugar for a.concat(b), a<b> for arrays would be just syntactic sugar for a.get(b) and so on. (Having to use <> instead of square brackets.)
A clarification: this proposal only applies to arrays of reference types, not primitive types. This is because collections (and generics) only deal with reference types.
Re the fact that the JVM wouldn't understand that a native array can be passed to a method which takes (say) a List parameter - yes this is an important point. At a guess I can see 2 solutions to this (haven't really thought it through yet):
(1) Whatever happens it would be necessary for the JVM 'checkcast' instruction to be changed to allow casting between arrays and Array (or its superclasses/superinterfaces). The compiler could insert such a cast when passing an array to a method which expects (say) a List parameter.
(2) These extra casts might be unnecessary, if all the JVM instructions were changed so that they just 'know' that native arrays implement AbstractList. Currently the bytecodes 'know' that arrays implement Object, e.g. an array can be passed to a method which expects an Object parameter. The bytecode specs could be changed so that arrays are known to implement AbstractList not just Object.
No doubt there are lots of details to be worked out (by someone who knows more about compilers than me) but this idea seems possible in principle.
Similar Messages
-
What types of sort performed by sort method of Array class ?
I use normal bubble sort and method Array.sort() to sort some given data of an Array and then count the time.But Array.sort() method takes more time then normal bubble sort.
Can anybody tell me what types of sort performed by sort method of Array class?I'm pretty sure that in eariler versions (1.2, 1.3
maybe?) List.sort's docs said it used quicksort. Or I
might be on crack.You are actually both correct, and wrong :)
From the documentation of the sort methods hasn't changed in 1.2 -> 1.4 (as far as I can notice), and the documentation for sort(Object[]) says (taken from JDK 1.2 docs):
"This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.
The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n*log(n) performance, and can approach linear performance on nearly sorted lists."
So, how could you be correct? The documentation for e.g. sort(int[]) (and all other primities) says:
"Sorts the specified array of ints into ascending numerical order. The sorting algorithm is a tuned quicksort, adapted from Jon L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function", Software-Practice and Experience, Vol. 23(11) P. 1249-1265 (November 1993). This algorithm offers n*log(n) performance on many data sets that cause other quicksorts to degrade to quadratic performance."
Your memory serves you well :)
/Kaj -
Extending Array class, get Error #1069: Property 0 not found with indexOf call
I'm using inheritance to extend the Array class to create a Paths class that moves Sprites/MovieClips around on the screen. I'm getting an odd error on a call to indexOf. Here's the error:
ReferenceError: Error #1069: Property 0 not found on Paths and there is no default value.
at Array$/_indexOf()
at Array/http://adobe.com/AS3/2006/builtin::indexOf()
at Paths/Next()[D:\Stephen\Documents\Flash\TossGame\TossGameFirstPerson\Paths.as:40]
Here's the relevant code in the Paths class:
public class Paths extends Array
private var cCurrentPath:Path;
public function Next():Path
var lArray:Array = this;
var lNextIndex:int = indexOf(cCurrentPath) + 1;
if (lNextIndex == length) lNextIndex = 0;
var lPath:Path = lArray[lNextIndex];
return lPath;
} // class
I get the error at the highlighted line. cCurrentPath is populated with a Path object which is the object located at position 0 of the this object (Paths). I've tried the following variants of the Next() function:
public function Next():Path
var lArray:Array = this;
var lNextIndex:int = lArray.indexOf(cCurrentPath) + 1;
if (lNextIndex == lArray.length) lNextIndex = 0;
var lPath:Path = lArray[lNextIndex];
return lPath;
public function Next():Path
var lArray:Array = this;
var lNextIndex:int = this.indexOf(cCurrentPath) + 1;
if (lNextIndex == this.length) lNextIndex = 0;
var lPath:Path = lArray[lNextIndex];
return lPath;
public function Next():Path
var lArray:Array = this;
var lNextIndex:int = super.indexOf(cCurrentPath) + 1;
if (lNextIndex == super.length) lNextIndex = 0;
var lPath:Path = lArray[lNextIndex];
return lPath;
Same error happens whichever I try. Anyone got any ideas?
Stephen
Flash Pro CS3 (Version 9.0)Mark your class dynamic.
public dynamic class Paths extends Array -
consider the code below
int[] list = {2, 4, 7, 10};
java.util.Arrays.fill(list, 7);
java.util.Arrarys.fill(list, 1, 3, 8);
System.out.print(java,util.Arrays.equals(list, list));i understand line 2, it gonna fill 7 into the array,so the output would be Line 2: list is {7, 7, 7, 7}
my question is line 3, how come the output would be {7, 8, 8,7} what does 1 and 3 represent in a arrary?
the line 4 output would be {7, 8,8,7} again why?
Thank you guys whoever is gonna take to respond me questionszerogpm wrote:
but which 2 lists were comparing ? since i have list list with the same name1) You're not comparing lists, you're comparing arrays.
2) You're comparing a single array with itself.
3) Objects, including arrays, do not have names. Classes, variables, and methods have names. Objects do not. -
I want to define a new method to search arrays for specific
values.
I have a new class defined like this:
class Array2 extends Array{
function Array2(){
function myMethod(){
In my code I use this line to declare a new instance:
var myArray:Array2=new Array2(1,2,3,4,5);
If I now use use:
trace(myArray[1]);
it returns 'undefined'. What is the reason for this and is
there a way round it?
If I define the myArray without any values and then use the
push() method it seems to work but I need Array2 to work exactly
the same as Array only with some additional methods.
Cheers for any and all helpCheers JPK that works well. I am confused about the super()
statement though as if you remove it from the last example it still
works.
The help file suggests that you should be able to use:
functio Array2(){
super(arguments);
but if I do and then create an instance with ...new
Array2(1,2,3,4);
it makes an array with one node only containing the string
"1,2,3,4"
This is all beside the point really as I can now make it work
at least (thank again everyone) but I would like to understand
exactly what is going in the background here so please keep posting
any findings.
NIce nice nice :) -
Reflection question: Creating dynamic array classes
I'm trying to create a String[].class dynamically by passing into a method the value "String[]" and then returning the Class, but I can't get my head around creating an array version.
e.g.
public Class classFromName(String className)
return Class.forName(className);
but it fails on arrays passed in. Fine for "String", but not "String[]" or "String[][]".
Is this possible?
Thanks
Mark Fisher ([email protected])I couldn't get just "String" to work.
But remember that you usually write just "String" in source code because there's an implicit import java.lang.* statement at the beginning of your Java source code. That means that "java.lang.String" is the full name of the class. Imports apply onto to source code and are not "remembered" after the compilation process is finished.
If you want an array of Strings, the JVM name for that class is "[Ljava.lang.String;". I think there's also a way of getting the class object for array types in the reflection classes... I'll let you look for that in the API docs. -
I've added a number of new methods to the Array object in Javascript. My scripts see them fine, but the Web console reports them as 'undefined'. Apparently the console cannot see my changes. Why is that?
Not the same. It should be like the orange indicator for an imported clip in the camera import window. It's really quite sophisticated in iMovie. When you switch projects the orange line changes to reflect what's in the open project so a clip might have the orange indicator when one project is open in the timeline, and not when another project is open. It's a really useful tool, because it even shows what parts of a clip have been used in the open project.
-
Creating an array of objects of a class known ONLY at RUNTIME
I have a method in a class which expects an array of objects of particular type (say A) as its only argument. I 'invoke' this method using reflection. I have the instances of the class A stored in a Vector. When I do 'toArray' on this vector, what I get back is an array of Objects and not an array of objects of A. I assign this array to the zeroth element of another Object array and pass that array as a second argument to the 'invoke' method. Of course, it throws an Exception saying - argument types mismatch. Because I am sending an array of Objects to a method expecting an array of objects of A. My problem is I don't know A until runtime. So I have to handle whatever I am getting back after doing 'toArray' on a vector as a Generic Object. I know there's another version of 'toArray' in the Vector class. But it's API documentation didn't help a lot.
Can anybody please help me solve this problem? Any sort of hints/code snippet would be of great help.
Does the above description makes any sense? If not, please let me know. I would try to illustrate it with a code sample.
Thanks a lot in advance.Sorry, for the small typo. It is -
clazz[] arr = (clazz [])java.lang.reflect.Array.newInstance(clazz, n);
instead
Thanks for the reply. I could do this. But I am
getting a handle to the method to be 'invoke'd by
looking at the types of the parameters its
expecting(getParameterTypes). So I can't change it to
accept an array of Generic Objects.
I looked at the java.lang.reflect.Array class to do
this. This is what I am trying to do-
String variableName is an input coming into my
program.
n is the size of the array I'm trying to create.
Class clazz = Class.forName(variableName);
clazz[] arr = (clazz
[])java.lang.reflect.newInstance(clazz, n);
According to Reflection API, it should work, right?
But compiler yells at me saying 'class clazz not
found'.
Any suggestions/hints/help?
Thanks, again. -
Which class is java array??
for example, a 'name' array.
To see its length, use the reference name, ---> name.length
so I conclude that name's array class must have the static varriable length.
but what is that class?? where is it in the API??Do you mean this class is only implemented byJVM??
Yep.
ie, an array type could have any name??I believe the JLS specifies what array class names
will be.
public class ArrayTypes {
public static void main(String[] args) throws
rows Exception {
System.out.println(new
ntln(new byte[0].getClass().getName());
System.out.println(new
ntln(new char[0].getClass().getName());
System.out.println(new
ntln(new short[0].getClass().getName());
System.out.println(new
ntln(new int[0].getClass().getName());
System.out.println(new
ntln(new long[0].getClass().getName());
System.out.println(new
ntln(new float[0].getClass().getName());
System.out.println(new
ntln(new double[0].getClass().getName());
System.out.println(new
ntln(new boolean[0].getClass().getName());
System.out.println(new
ntln(new Object[0].getClass().getName());
System.out.println(new
ntln(new ArrayTypes[0].getClass().getName());
System.out.println(new
ntln(new ArrayTypes[0][0].getClass().getName());
System.out.println(new
ntln(new int[0][0].getClass().getName());
[B
[C
[S
[I
[J
[F
[D
[Z
[Ljava.lang.Object;
[LArrayTypes;
[[LArrayTypes;
[[I
Very cool experiment there jverd. That gets props from me. -
Public class ArrayEx extends Array
Hi, I'm very bad at OO programming, but I'm trying to learn.
I want to add some functions to my Arrays, like checking if
arrays contain a value (indexOf can be equal to 0, which is false,
though actually I'm used to the loose data typing of as2, so this
may not be quite true. Bear with me though, I want to learn how to
extend a class). So I'm trying to write a class that extends the
basic Array class.
I am confused about the constructor, I want to mimic the
behaviour of the Array class but I'm not sure if I need to write
functions for each method of Array. Since my ArrayEx extends the
Array class it should inherit the array functions right? So it
should already have .pop() and .push() ext. defined? How should I
write my constructor to store the data the same way as the Array
class does though?
Is there somewhere I can look at the internal Array class to
figure out how it does it?
What I have written so far appears at the bottom of the
message. I include questions as comments.
I hope someone can help me out. I'm sorry if I'm asking stuff
that seems obvious. Thanks for your time.
JonI've found the solution to my second set of problems and
since I chose to trouble you all with the question I thought I'd
post the answer.
First problem, I had declared the ArrayEx class as dynamic
but not as public. Should read;
dynamic public class ArrayEx extends Array{
Second problem. An empty constructor function, by default,
calls the parent constructor function with no arguements. Since I
wanted to construct my new array class like the default array class
i had to add some code to handle that.
So here is the working class; -
Compile error on .class for an array.
How do I write the code below correctly?
final ArgumentCaptor<MessageToken[]> tokenArg = ArgumentCaptor.forClass(MessageToken[].class);How do I write the code below correctly?
final ArgumentCaptor<MessageToken[]> tokenArg = ArgumentCaptor.forClass(MessageToken[].class);
What is the exact compilation error?
Note that since ArgumentCaptor is probably a custom class that only you or your team knows about, we will maybe not be able to help a lot, we will probably need that you give us the signature of its method forClass
Note that the problem is not that the syntaxfor the array class MessageToken[].class is illegal in itself; the following compiles perfectly:
public class TestClassLitteral {
Class stringClass = String.class;
Class stringArrayClass = String[].class;
} -
Setting Array of class field from C++
Hi,
Consider I have two class
Class A{
B[] bclasses;
Class B{
int first;
int second;
Now i have
jclass ACls= env->FindClass("A");
How to create array of B, get the fields of B, assign value of B and assign array of B from C++ to Java. Please explain with exampleFor each B
-Get the class (do it the first time.)
-Create the instance
-Call the construtor
-Get each member variable.
-Set the value of each member variable.
To do A
-Get the class (do it the first time.)
-Create the instance
-Call the construtor
-Get each member variable.
-Set the value of each member variable - as an array
. - Get array class
. - Create instance
. - Initialize each array index using the B method above. -
Displaying the contents of an array of objects
Hello All,
My Java teacher gave us a challenge and I'm stumped. The teacher wants us to display the contents of the array in the main menthod. The original code is as follows:
public class TestObjects
public static void main ( String args[] )
Thing[] thingArray = { new Thing(4), new Thing(7) };
}I understand that the elements of the array are objects, and each one has a value assigned to it. The following code was my first attempt at a solution:
public class TestObjects
public static void main ( String args[] )
Thing[] thingArray = { new Thing(4), new Thing(7) };
for ( int i = 0; i < thingArray.length; i++)
System.out.println( thingArray );
}To which I'm given what amounts to garbage output. I learned from reading about that output that its basically displaying the memory location of the array, and the the contents of the array. There was mention of overriding or bypassing a method in System.out.println, but I don't believe that we're that far advanced yet. Any thoughts? I know I have to get at the data fields in the objects of the array, but i'm not having an easy time figuring it out. Thanks very much in advance!robrom78 wrote:
public class TestObjects
public static void main ( String args[] )
Thing[] thingArray = { new Thing(4), new Thing(7) };
for ( int i = 0; i < thingArray.length; i++)
System.out.println( thingArray );
Note that you're trying to print the entire array at every loop iteration. That's probably not what you meant to do.
You probably meant to do something more like
System.out.println( thingArray[i] );Also, note that the java.util.Arrays class has a toString method that might be useful.
To which I'm given what amounts to garbage output. It's not garbage. It's the default output to toString() for arrays, which is in fact the toString() defined for java.lang.Object (and inherited by arrays).
I learned from reading about that output that its basically displaying the memory location of the array, and the the contents of the array.It displays a default result that is vaguely related to the memory, but probably shouldn't be thought of us such. Think of it as identifying the type of object, and a value that differentiates it from other objects of the same type.
By the way I assume you mean "+not+ the contents of the array" above. If so, that is correct.
There was mention of overriding or bypassing a method in System.out.println, but I don't believe that we're that far advanced yet. Any thoughts? No, you don't override a method in println; actually methods don't contain other methods directly. You probably do need to override toString in Thing.
I know I have to get at the data fields in the objects of the array, but i'm not having an easy time figuring it out. You can get to the individual objects in the array just by dereferencing it, as I showed you above.
But I suspect that won't be sufficient. Most likely, Thing doesn't have a toString method defined. This means that you'll end up with very similar output, but it will say "Thing" instead of "[Thing" and the numbers to the right of the "@" will be different.
You'll need to override the toString() method in Thing to get the output you want. -
I am unable to figure out the way in which I can return an object
array from a cpp file to java. Is there any obvious error which you can spot in
my CPP file?
When I try to return a single object in the native function,
it works fine but when I try to extend it and return an array of the object, it
throws an error.
Please find below the details
h1. Java Class
public class Flight {
public String ID;
public class InterfaceClass {
private native Flight[] GetFlights();
public static void main(String[] args)
Flight[] objFlight = new
InterfaceClass().GetFlights();
System.+out+.println(objFlight[0].ID);
static {
System.+loadLibrary+("main");
h1. CPP File
JNIEXPORT jobjectArray JNICALL Java_InterfaceClass_GetFlights(JNIEnv env, jobject obj)
//1. ACCESSING THE FLIGHT CLASS
jclass cls_Flight = env->FindClass("LFlight;");
//2. CONSTRUCTOR FOR FLIGHT CLASS
jmethodID mid_Flight = env->GetMethodID(cls_Flight,"<init>", "()V");
//3. CREATING AN OBJECT OF THE FLIGHT CLASS
jobject objFlight = env->NewObject(cls_Flight, mid_Flight);
//4. ACCESSING THE FLIGHT's "ID" FIELD
jfieldID fid_ID = env->GetFieldID(cls_Flight, "ID","Ljava/lang/String;");
//5. SETTING THE VALUE TO THE FLIGHT's "ID" FIELD
env->SetObjectField(objFlight,fid_ID, env->NewStringUTF("ABC"));
//6. ACCESSING THE FLIGHT ARRAY CLASS
jclass cls_Flight_Array = env->FindClass("[LFlight;");
if(cls_Flight_Array == NULL)
printf("Error-1");
//7. CREATING A NEW FLIGHT ARRAY OF SIZE 1 jobjectArray arrFlightArray = env->NewObjectArray(1,cls_Flight_Array,NULL);
if(arrFlightArray == NULL)
printf("Error-2");
//8. INSERTING A FLIGHT BJECT TO THE ARRAY
env->SetObjectArrayElement(arrFlightArray,0,objFlight);
return arrFlightArray;
h1. Error
# A fatal error has been detected by the Java Runtime Environment:
# EXCEPTION_ACCESS_VIOLATION
(0xc0000005) at pc=0x6d9068d8, pid=1804, tid=3836
# JRE version: 6.0_18-b07
# Java VM: Java HotSpot(TM) Client VM (16.0-b13 mixed mode, sharing
windows-x86
# Problematic frame:
# V [jvm.dll+0x1068d8]
# An error report file with more information is saved as:
# C:\Users\Amrish\Workspace\JNI Test\bin\hs_err_pid1804.log
# If you would like to submit a bug report, please visit:
http://java.sun.com/webapps/bugreport/crash.jsp
C:\Users\Amrish\Workspace\JNI Test\bin>java -Djava.library.path=.
InterfaceClass
Exception in thread "main" java.lang.ArrayStoreException
at
InterfaceClass.GetFlights(Native Method)
at
InterfaceClass.main(InterfaceClass.java:6)
C:\Users\Amrish\Workspace\JNI Test\bin>java -Djava.library.path=.
InterfaceClass
Exception in thread "main" java.lang.ArrayStoreException
at
InterfaceClass.GetFlights(Native Method)
at
InterfaceClass.main(InterfaceClass.java:6)
Edited by: amrish_deep on Mar 18, 2010 7:40 PM
Edited by: amrish_deep on Mar 18, 2010 7:40 PM//6. ACCESSING THE FLIGHT ARRAY CLASS
jclass cls_Flight_Array = env->FindClass("[LFlight;");The argument to NewObjectArray is the +element+ class of the array you're about to create, not the +array+ class itself. -
How can i access the methods if i only got the java class file?
just like what the topic said...i would like to ask if i only got the class file of java without API documentation. how can i know what method is included ?
thanks a lot.
my email address is : [email protected]Class.getMethods()
throws SecurityException
Returns an array containing Method objects reflecting all the public member methods of the class or interface represented by this Class object, including those declared by the class or interface and and those inherited from superclasses and superinterfaces. The elements in the array returned are not sorted and are not in any particular order. This method returns an array of length 0 if this Class object represents a class or interface that has no public member methods, or if this Class object represents an array class, primitive type, or void.
Maybe you are looking for
-
Step by Step Instructions for Installing Self Signed Certificate using Certificate Modification Tool
I am looking for some step by step instructions for installing the self signed certificate from my Microsoft SBS 2003 server on a Treo 755p and 750p. In particular I need some help with the form of the actual certificate and how to use the Certifica
-
Is CS4 compatible with Windows 8 Pro?
Is CS4 compatible with Windows 8? If yes, then what procedure should be followed upgrading from Vista (64-bit) to Windows 8 Pro? Pls advise and all help would be appreciated.
-
Desktop Software won't download device updates?
Hi, I recently bought a BB Torch and would like to add more language supports via the Desktop Software (ver. 6). However, the installer won't go past the back up phase as the update window immediately closes upon entering the 'downloading device soft
-
Hi, I am Java Developer !
-
Hi. Please, using mysql, it is possivel to create a new register in the table, being used the easinesses of the Entity Object? If YES, how to? I use JDeveloper 10.1.3.1.0. MySQL 4.0 An emabrace, CarloSilva