Returning Generic Arrays
I'm trying to return an Array like such:
public T[] main = (T[]) new Object[100];
public int tracker = 0;
public void getArray() {
T[] temp = (T[]) new Object[tracker];
for(int x = 0; x < temp.length; x++) {
temp[x] = main[x];
return temp;
}It's part of a dynamic array im creating and this function return the actual trimmed array of type T but i've narrowed the problem down to be the actual assignment on the other side - for example if I was to write:
private DArray<PolyGon> polygons = new DArray();
private PolyGon[] test = polygons.getArray();This is where I get the error - can anyone explain why?
yeh, sorry that was a typo but in my real source code I had
public T[] getArray() and it still gives me a runtime exception - if I had put public void getArray() it wouldn't have compiled
Similar Messages
-
Describe non-generic array cast in JLS3 as being unchecked
This method :
static <T, U extends T> U[] cast(T[] a) { return (U[]) a; }will generate the warning: [unchecked] unchecked cast, found: T[], required: U[].
And it should. Wouldn't it be appropriate if
static Object[] cast(String[] a) { return (String[]) a; }would produce the same warning?
If you do that, you could translate the declaration
T[] at = new T[255]
String[] as = new String[255]into
Array<T> at = Array.<T>newInstance(255);
Array<String> as = Array.<String>newInstance(String.class, 255);where java.lang.reflect.Array would be something like
package java.lang.reflect.Array;
public final class Array<T> implements Iterable<T> {
public final int length;
private Type memberType;
private Array(Type memberType, int length) {
this.memberType = memberType;
this.length = length;
public native T getMember(int i);
public native void setMember(int i, T member);
public native java.util.Iterator<T> iterator();
public static <U> Array<U> newInstance(int length) {
return new Array<U>(null, length);
public static <U> Array<U> newInstance(Class<U> memberClass, int length) {
return new Array<U>(memberClass, length);Sorry, I created a bad example. It should have been:
static <T, U extends T> T[] cast(U[] a) { return (T[]) a; }and
static Object[] cast(String[] a) { return (Object[]) a; }The point is that an array of String is different from an array of Object and casts between them is unsafe. Throwing an ArrayStoreException if the wrong type is assigned is just a workaround for lack generic types in pre-Tiger Java. Now that we will have generics, I think it would be appropriate if Java arrays would be treated as proper generic types. For those that are afraid of breaking backwards compatiblility, the erasure mechanism should be able to take care of that. -
My generic array creation problem.
I'm getting a "generic array creation" error on lines 6 and 14. I've googled it and I'm still having a hard time. Most things I find on it are pretty complicated and as you can see mine's not, I'm in a beginners course. I'm basically writing a class with methods for dealing with a file of donors.
Here's my code:
public class DonorList <dlist>
//Create empty list
public DonorList()
storage = new dlist [MAX];
count = 0;
//Capacity as specified
public DonorList (int cap)
MAX = cap;
storage = new dlist [MAX];
count = 0;
public boolean isEmpty()
return count == 0;
public void clear()
count = 0;
//Returns number of elements
public int size()
return count;
//Item at position k, position starts at zero
public dlist get (int k)
if (k >= 0 && k < count)
return storage [k];
return null;
// e becomes item at position k
public dlist set (int k, dlist e)
dlist old = null;
if (k > 0 && k < count)
old = storage [k];
storage [k] = e;
return false;
//Returns the position of e or -1 if not found.
public int indexOf (dlist e)
int k;
for (k = 0; k < count; k++)
if (e.equals(storage[k]))
return k;
return -1;
//Appends e at the end of the list. Returns false on failure.
public boolean append (dlist e)
if (count < MAX)
storage [count] = e;
count ++;
return true;
return false;
//Adds e at position k. Returns false on failure.
public boolean add (int k, dlist e)
int j;
if (count == MAX || k < 0 || k > count)
return false;
for ( j = count; j > k; j--)
storage [j] = storage [j-1];
storage [k] = e;
count ++;
return true;
return false;
private int MAX = 100;
private dlist [] storage;
private int count;
}Any help as to why I am getting these errors is very much appreciated. Thanks.You cannot create an array of a generic, instead you need to create an array of the class the generic extends (in this case Object)
You then have to cast the array to the generic type which will give you an unchecked warning which you can turn off with @SuppressWarning("unchecked") on the class.
Generics and arrays don't always play nicely together and this is one case. ;-) -
Information from formula that returns an array is not shown on chart
Hello experts,
I have a chart (combination) which should show information from a group of cells that have a formula in it and returns an array ().
{=SUM((Plan1!L2:L43=L2)(Plan1!I2:I43=D3)Plan1!M2:M43)}
In the spreadsheet and on the chart, while developing the dashboard, it shows perfectly.
What happens is that while previewing.....no data is shown at all on the chart.
Please advise on how to solve it.
Carlos Henrique Matos da Silva - SAP BusinessObjects BI - Brazil.Hi Carlos,
Excel Array entered formulae are not supported in Xcelsius.
When you are designing the dashboard Xcelsius is using native Excel functrionality and calculation engine to display the results. When you preview the dashboard Xcelsius convertys all of the spreadsheet formulae to Flash/ActionScript which does not have the equivalent array functionality, adn so when previewed the results do not show.
Hope this helps
Charles -
Returning an array type from a local method in Web Dynpro Java application
Hi,
In my project, we have a requirement to display 18 rolling months along with the year, starting from current month.
How I am going to approach is that I will get the system date and get the current month and send the month and year value to a local method which will return 18 rolling months along with the year.
But, when I tried to create a new method there is no option to return an array type. It was greyed out.
So, we can not return an array type from a method from Web Dynpro for Java application?
If so, what is the alternative and how am I going to achieve it?
I will appreciate your help!
Regards
RamHI
You can create new methods in
//@@begin others
private ArrayList MyMethod(){
// ** Put your code here
return new ArrayList();
//@@end
Other option are create a context node with cardinality 0...n with one or more attributes, and in your method create the needed registers into this node. To read this values, you only need to read your context node.
Best regards
Edited by: Xavier Aranda on Dec 2, 2010 9:41 AM -
BPEL build error when invoke an extrenal Web Service that returns an Array
Hello,
I built with JDeveloper a web service that returns an Array of Java Bean classes and I try to invoke this web service from a BPEL process. The wsdl file is automatically generated by the JDev. When I built the BPEl project I obtained the following error:
[bpelc] [Error] :-1:-1: src-resolve.4.2: Error resolving component 'SOAP-ENC:Array'. It was detected that 'SOAP-ENC:Array' is in namespace 'http://schemas.xmlsoap.org/soap/encoding/', but components from this namespace are not referenceable from schema document 'http://malangiu-ro:8988/cde-Project-context-root/CdeFactoryWS?WSDL'. If this is the incorrect namespace, perhaps the prefix of 'SOAP-ENC:Array' needs to be changed. If this is the correct namespace, then an appropriate 'import' tag should be added to 'http://malangiu-ro:8988/cde-Project-context-root/CdeFactoryWS?WSDL'.
[bpelc] [Error] :-1:-1: src-resolve.4.2: Error resolving component 'SOAPENC:Array'. It was detected that 'SOAPENC:Array' is in namespace 'http://schemas.xmlsoap.org/soap/encoding/', but components from this namespace are not referenceable from schema document 'http://malangiu-ro:8988/cde-Project-context-root/Top300FactoryWS?WSDL'. If this is the incorrect namespace, perhaps the prefix of 'SOAPENC:Array' needs to be changed. If this is the correct namespace, then an appropriate 'import' tag should be added to 'http://malangiu-ro:8988/cde-Project-context-root/Top300FactoryWS?WSDL'.
[bpelc] [Error] :-1:-1: src-resolve.4.2: Error resolving component 'SOAP-ENC:Array'. It was detected that 'SOAP-ENC:Array' is in namespace 'http://schemas.xmlsoap.org/soap/encoding/', but components from this namespace are not referenceable from schema document 'http://malangiu-ro:8988/cde-Project-context-root/CdeFactoryWS?WSDL'. If this is the incorrect namespace, perhaps the prefix of 'SOAP-ENC:Array' needs to be changed. If this is the correct namespace, then an appropriate 'import' tag should be added to 'http://malangiu-ro:8988/cde-Project-context-root/CdeFactoryWS?WSDL'.
Any hint? Thanks in advance!
Regards,
MarinelHi,
BPEL and BPEL PM do not have a good support for SOAPENC-Array: it would be very difficult to create such an array in BPEL or to receive it and manipulate it.
The (unfortunately very intrusive) work around is to change the WSDL of the service to use a XML type defined using XML schema. This is all the more painful that JDev 9.0.4 does not have strong support for complex types.
In general though, I would highly recommend this best practice:
1) Start by define the WSDL contract first
2) Then generate the server side skeleton to implement it
3) Use BPEL as the client to this contract.
By starting with the contract first, you make sure that 1) your interfaces are clean and coarse grained.
2) things like java objects, sessions, etc to not leak through the interface (which would be the worst thing that could happen because it would closely link the client and the server.
Sorry for not being more helpful. This will get radically cleaner in Oracle AS 10.1.3.
Edwin -
Return String array in server side
i wrote a bean which contains a function return String array (
String[] ). It shows no error on compile time, and also in
generate jar file. However, when i generate it to an ear file,
the syntax of the wsdl file is not correct so the client can't
call this function becuase the xml can't parse the wsdl.
When i change the return type to String, everything is ok. Does
anybody know what's happen? I really have no idea on it, thx.This is why I wanted to see some code. I wanted to see how you are trying to move the array from one class to another.
This should work... provided that the array is initialised correctly in ClassA. If you are doing it like this, please post some code and I'll help you fix it.
class ClassA{
public String[] getMyArray(){
return myArray;
class ClassB{
public void myMethod(){
ClassA myA = new ClassA();
String[] newArray = myA.getMyArray();
} -
External java function that should return String array
Hi everyone,
I have a split function in plsql that takes 10 times longer a java tokenizer function that i was written. So, i want to use java external function to split my plsql strings into pieces.
I can write a java external procedure that returns types like int, float and String types. I have no problem about it.
My problem is returning an array of strings. I found a book that has an example about how can we get directory list in plsql with java external procedure.
(code)
import java.io.File;
import java.sql.*;
import oracle.sql.*;
import oracle.jdbc.*;
public class JFile {
public static oracle.sql.ARRAY dirlist (String dir)
throws java.sql.SQLException
Connection conn = new OracleDriver().defaultConnection( );
ArrayDescriptor arraydesc =
ArrayDescriptor.createDescriptor ("DIRLIST_T", conn);
File myDir = new File (dir);
String[] filesList = myDir.list( );
ARRAY dirArray = new ARRAY(arraydesc, conn, filesList);
return dirArray;
CREATE OR REPLACE FUNCTION dirlist (dir IN VARCHAR2)
RETURN dirlist_t
AS
LANGUAGE JAVA
NAME 'myFile.dirlist(java.lang.String) return oracle.sql.ARRARY';
(code)
I could compile this source file in localhost but not remotehost. There are jar files ( import oracle.sql.*; import oracle.jdbc.*; ) that should be added to remote classpath. ( others have already added java classpath ). But, which classpath i should add? Oracle has own JVM and Classpath, probably i should upload these jar files to oracle classpath. Am i wrong? How can i do? Can you explain in detail? How can i return string array from java external function in Oracle ?
I am using Oracle 11.1.0.7 on Solaris Sparc Machine.Hi,
What do you mean "compile in remote host"
Aren't you using the loadjava tool? - that should be enough, the RDBMS already "has" the jars needed.
[A must read|http://download.oracle.com/docs/cd/B28359_01/java.111/b31225/chone.htm#BABCFIIF]
Regards
Peter -
How to define method witch returning an array in View, using method wizard
Dear experts.
I would like to define method which returning an array in View.
When View is opened, in "Methods" tab push "new" button, then select "Method" in Method Type window,
push "Next" but in Method Properties window Array Type checkbox is disabled. So, it is not possible to
define method with returning array type.
Please anybody, help me to resolve this problem.Hi
While creating method, you can see a check box over there as array type just check it that array type check box,
or
You can selet java native type as array by selecting "java native type"
thanks
anup
Edited by: Anup Bharti on Oct 15, 2008 8:50 AM
Edited by: Anup Bharti on Oct 15, 2008 8:51 AM -
Hi,
I am trying to return an array of byte from JNI to java. I read the tutorial but i still find it hard to understand.
BYTE *encoded is the variable that has the contents to be sent back to java.
jbytearray jb=encoded;
ret jb;
This does not seem to reurn anything!! Please helpThis is the JNI implementation of the method:
public native byte[] returnArray (int size, byte initialValue).
JNIEXPORT jbyteArray JNICALL Java_Test_returnArray
(JNIEnv *env, jobject This, jint size, jbyte initialValue) {
//-- No error handling is being done...
jbyte* buf = new jbyte[size];
memset (buf, initialValue, size);
jbyteArray ret = env->NewByteArray(size);
env->SetByteArrayRegion (ret, 0, size, buf);
delete[] buf;
return ret;
}A jbyte is a signed char (a signed byte). You can mix signed bytes and unsigned bytes in C++ depending on your needs. This JNI method is the functional equivalent of the 100% Java function:
public byte[] returnArray (int size, byte initialValue) {
byte[] ret = new byte[size];
for (int i = 0; i < size; ++i) {
ret[i] = initialValue;
return ret; -
Trying to fetch a value in a java function and returning the array.
hello....I am trying to fetch a value in a java function and returning a array......I already write the pl/sql function which is working fine....but i think i m lost......when i run it through the jsp it shows me error........pls help
java code:=
public String [] viewx(String bid) throws SQLException, Exception {
String [] values;
try {
CallableStatement cstmt = null;
String SQL = "{?=call vi_dis.v_dis(?)}";
cstmt = con.prepareCall(SQL);
cstmt.registerOutParameter(1,Types.ARRAY);
cstmt.setString(2, bid);
cstmt.execute();
Array simpleArray = cstmt.getArray(1);
values = (String [])simpleArray.getArray();
cstmt.close();
} catch (SQLException sqle) {
error = "SQLException: Could not execute the query.";
throw new SQLException(error);
} catch (Exception e) {
error = "An exception occured while retrieving emp.";
throw new Exception(error);
return values;
pl/sql function
create or replace package vi_dis
as
function v_dis(vbid IN student.bid%type) return stuarray ;
end;
create or replace
package body vi_dis
as
function v_dis(vbid IN student.bid%type) return stuarray
is
l_stu stUarray :=stuarray();
cursor c_sel
is
SELECT CNAME
FROM COURSE C,ENROLL E
WHERE C.CID=E.CID
AND E.BID=vbid;
BEGIN
OPEN c_sel;
FETCH c_sel BULK COLLECT INTO l_stu;
l_stu.extend;
CLOSE c_sel;
RETURN l_stu;
EXCEPTION
WHEN NO_DATA_FOUND
THEN DBMS_OUTPUT.PUT_LINE('NO RESULT AVAILABLE');
CLOSE c_sel;
END;
END;
/BalusC wrote:
It is comparing the selected value against the List<SelectItem> returned by getSetoresOrigem() as it is during the apply request values phase of the form submit request.Ok. That's what I supposed JSF was doing.
BalusC wrote:
If the selected value isn't in there, then you will get this error.I can understand this, but is this right? As I said, the old value isn't really there because I changed the list values to new ones. But the new value (the value of fSetorOrigem ) corresponds to a value that exist in the new list items, so a valid value. So JSF is not considering that I also changed the list, not just the value. It is comparing the new value with the old list, not the new one. Acting like this JSF is making the page looks like a static HTML page, not a dynamic one. If I can't change the list and the value, what's the point of that? In my point of view I'm not doing anything wrong, I'm not violating any JSF rules.
Marcos -
Return an array from dll to labview
Hello,
I am using "Call Library Function" where I call a C function from Labview.
Now .. I want to return an 1 dimensional array from C DLL back to Labview.
Can someone provide an example code how to do it.
When I configure parameter, there are options "Array Data Pointer", "Array Handle" and "Array Handle Pointer".
When I take the first (the simple one), so there is no way labview can know how many items are in the array.
But what is the right to take?
Thanks in advance
Kind RegardsYou would run into the same problem calling a function that returns an array in C, because you cannot determine the number of items in an array in C solely from the pointer value that a function returns. Also, it's a bad idea to return an array of unknown size as a function's return value, because that makes the calling function responsible for deallocating the memory even though the called function allocated it. If you don't know in advance how large the array will be, then a better approach is to allocate an array of sufficient size in the calling function (or in LabVIEW, in this case) and pass that by reference to the function, then have the function's return value indicate the number of values in the array that are actually filled with data.
-
Unable to compile .ear file with an operation that returns an array
Hi
God, hopefully someone can help me.....
I have a web service that has various operations, one of which is attempting to return an array of strings. I am declaring a complextype in the WSDL that should functions as the array like this:
<schema.....
<element name="result" type="string"/>
<complexType name="searchResponseElement">
<sequence>
<element ref="tns:result" maxOccurs="unbounded"
minOccurs="0"/>
</sequence>
The error I receive is utterly vague, just saying ' compilation error occurred' when I go to deploy the ear file. I did have this working with another methos of declaring an array i.e.
<schema...
<complexType name="searchResponseElement">
<complexContent>
<restriction base="soap11-enc:Array">
<attribute ref="soap11-enc:arrayType" wsdl:arrayType="xsd:string[]"/>
</restriction>
</complexContent>
</complexType>
But, I was trying to consume the webservice in an APEX application and that method did not return a tree structure that APEX was able to handle.
I really am losing my mind over this as I've had the same type of definition working before. Please, anyone - any clues???I answered this question that you also posted on stackoverflow.com.
-
Return an array of JButtons - Is this possible?
Is it possible to return an array of JButtons? I have madean array of JButtons and assigned them anonymous listeners as they each do the same thing so i only had to do one in the for loop creation
the idea is that i want to ship this code out to a method called createButtons and call it in the make frame method, but i cant seem to find a solution that actually works
thanksJustSomeGuy wrote:
If you went to your teacher and asked them how they felt about [the java forums], and under what circumstances it may be considered cheating, I think you will be suprised by the answer. Most teachers actually want you to learn, big shocker I know.
JSGJSG.kudos++;
compSciUndergrad wrote:
if you want to tell me your opinions i am all ears, i hope they are not to harsh :SI'm of the opinion that at least 90% of students who are concerned about being seen as cheating are only concerned because they feel that they are cheating. Furthermore atleast 90% of students who "feel" that they are cheating have perfectly valid concerns, because they are in fact cheating.
In my humble opinion it would be better for all concerned if cheaters did get caught, and sooner rather than later... because when they hit the real-world, where there really is no-one to cheat off, cheaters allways seem to come-a-cropper, big-time... because they also lie about there total lack of progress, in a shortsighted attempt to cover up there total imcompetence... too often taking those who entrusted them to actually do the friggin job down with them.
Lots of good people getting skinned-alive by a pack of feral know-nothing friggin lawers, all because some moron kid tells a pack of lies, and thinks he's gonna get away with it come crunch time. Ummm... No thanks. Ta.
So, much better to delineate between the competent and the not-competent programmer at the paedogogical stage. Eh what?
I wouldn't class posting a bit of code on a forum as lay-down-mazaire proof positive that "He's a cheat". My concern is that you are actively concerned (paranoid even), which is indicative that you have actually cheated in the past; and plan to do so in the future. That's all.
Cheers. Keith. -
When call a webservice opreation, it returns an array of complex type, sure, the calling is successed, but i don't know how to get the return values,
I have tried use Pendingcall.response & Pendingcall.getOutPutValues() in Pendingcall.onResult event function...
Waiting....Flash Lite doesn't fully support webservices, so you will find it difficult to use the full api set.
I suggest that you use SWX (swxformat.org) or simply HTTP requests for transactions.
We have a tutorial on use with ColdFusion here:
http://vimeo.com/6829083
Mark
Maybe you are looking for
-
Blackberry Screen Reader, features and functions
Gestures when using the Blackberry Screen Reader indicates that to "Pan or scroll a list" that an audio cue indicates that the scrolling action is complete, and the BlackBerry Screen Reader updates the point of regard so that you can continue reading
-
I was using Safari when the entire page suddenly went grey below the address bar. I can type in a new address and it will open, but the new page is also grey. Cannot scroll up or down or select anything on the page to link to. No problem with any of
-
Help: iTunes won't burn cds for me
I recently got a new laptop-- a Dell Inspiron 700m (Windows XP, Service Pack 2, etc.)-- and when I try to burn a playlist in iTunes, it says that my disc burner or software are not found. I'm able to drag and drop files onto the cd icon in my compute
-
Process chain is not activating
Hi , I am trying to schedule process chain, but giving error message like below. Job BI_PROCESS_TRIGGER Could not be activated (return code 8). Can you please tell me what it means and how can i activate it. Regards Rajini
-
Hp D330.audio driver installed but no voice.plz help.
hi i hav hp d330, X86 based PC with O.S wp pro.sp2. i installed bios update , networkind [lan card] drivers and they worked fine. I also download n installed Soundmax drivers one by one from http://h20000.www2.hp.com/bizsupport/TechSupport/Software