Creting object array with constructor
Hello all,
Here is a query kindly let me know your views.
Q) I want to create four objects and if i write a constructor how is it invoked..
kidly help me ...
thanks in advance
mahesh
Hello all,
Here is a query kindly let me know your views.
Q) I want to create four objects and if i write a
constructor how is it invoked..
kidly help me ...
thanks in advance
maheshYour question is very vague, very general, in short, impossible to really answer well. We need more specific information. A golden rule for forum questions: Please put as much effort into writing your question as you would wish someone would use answering your question.
I look forward to hearing more from you.
/Pete
Similar Messages
-
Invalid stored Object Types with Constructor Function
hi folks,
i created a stored object type on database 10.2. but it is invalid.
it has a constructor function and a number of member functions.
SQLPlus the only feddback is
Warning: Type Body is compiled with errors.
Toad 9.0.0 gives no error message.
how can i find out what kind of error there is? and where?
thx for help
joergIn SQL*Plus, when you get a warning that you've created an object with compilation errors, you can type
SQL> show errorsto see the list of errors.
Justin -
Object type with constructor gets PLS-00307 (10g)
Hi all,
I have the following code, and I am getting the following error. I want to have a constructor that can be called without specifying the parameters by name. Is that not possible?
What am I doing wrong?
Thanks!
Error:Error at line 50
ORA-06550: line 5, column 17:
PLS-00307: too many declarations of 'TRANSFEROBJECT_O' match this call
ORA-06550: line 5, column 5:
PL/SQL: Statement ignoredCode:DROP TYPE TransferObject_o
CREATE TYPE
TransferObject_o
AS OBJECT
m_objectId NUMBER(15)
, m_attribute VARCHAR2(4000)
, CONSTRUCTOR FUNCTION TransferObject_o
p_objectId NUMBER-- := NULL
, p_attribute VARCHAR2-- := NULL
) RETURN SELF AS RESULT
CREATE TYPE BODY
TransferObject_o
AS
CONSTRUCTOR FUNCTION TransferObject_o
p_objectId NUMBER-- := NULL
, p_attribute VARCHAR2-- := NULL
) RETURN SELF AS RESULT
IS
BEGIN
SELF.m_objectId := p_objectId;
SELF.m_attribute := p_attribute;
RETURN;
END;
END;
DECLARE
l_object TransferObject_o;
BEGIN
l_object := TransferObject_o(1, 'B');
END;
/Hi,
When you create an OBJECT, Oracle automatically creates a constructor with one argument for each of the object's attributes. You've created a second constructor, that has the same signature, except that the arguments in your functin are optional. When you call an overloaded routine ( whether it's a constructor or any other function or procedure), Oracle has to decide which of the versions you're calling. If you call the TransferObject_o constructor with fewer than two arguments, the system knows you mean the version you wrote, since the default constructor has two required arguments. But when you call the TransferObject_o constructor with exactly two arguments, it has no way of telling which version to use, and raises an error.
The Oracle 10.1 "PL/SQL User's Guide and Reference" says:
"You can define your own constructor methods, either overriding a system-defined constructor, or defining a new function with a different signature."
I couldn't find an example of overriding the constructor (not that I spent a lot of time looking. If you find one, or figure out how to do it, please post an example or a link here.).
Failing that, you can always give your constructor a different signature (e.g., put the VARCHAR2 argument first). -
Hi all,
first of all let's see some lines of source code
Foo.java
public class Foo
public Socket pSocket = null;
public nPosition = 0;
NewBie.java
public class NewBie{
public Foo[] m_Foo = null;
private int m_FooCount ;
public Init(int nFooCount)
m_Foo = new Foo[nFooCount];
m_FooCount = nFooCount;
public Operate()
int i = 0;
for( i= 0; i< m_FooCount; i++)
//follwing line will throw a exception
m_Foo.pSocket..... //Here is some operations with m_Foo[i].pSocket
Funny.java
public class Funny
public static NewBie m_pNewBie = new NewBie();
public static void main(String argv[])
m_pNewBie.Init(10);
m_pNewBie.Operate();
%>java Funny
Failed I/O:java.lang.NullPointerException
when I debug the program , seems m_Foo[i].pSocket in method Operate of NewBie object is null. I am puzzled, because I have created a NewBie object array with "new", why it still be null?
Any one can give me a detailed explaination? Thanks a lot.Arrays contain references, not objects. You must initialize the references within the array to point to constructed objects. Otherwise, the references will be null:
m_Foo = new Foo[nFooCount];
// m_Foo[0] is currently null -- the reference does not point to any object
m_Foo[0] = new Foo();
// now m_Foo[0] points to an object so is not null -
Populating a dynamic array with objects and managing it in runtime.
So I'm another stuck firstyear. I'll try and make my question compact. I'm using Flash CS6 and have drawn an animated character on the stage that consists of separate parts that are animated and its head is a separate class/symbol entirely because it has not only animation, but a state switch timeline as well. This said Head extends the Main that is the character MovieClip.
I am using a dynamic array to store and .push and .splice objects of another class that would collide with this said Head.
I also discovered the super() function that is implicitly called as the constructor of the parent in any child class that extends the parent, in this case Head extends Main. The issue is that my collidable object array is populated within the main, within the function that spawns every next collidable object with a TimerEvent. This said function then gets called twice due to the super() call.
I have tried putting this super() call into an impossible statement in my child class, but it doesn't change a thing, and it was said that this method is unsafe so I don't even know if it should be working.
However what confuses me the most is when I trace() the .length of my collidable object array at the end of that function. As I said earlier, the original function both spawns an object after a period of Timer(1000) and adds it to the stage as well as adds the object onto the object array, but the super() constructor only duplicates the length call and a creates a copy of the object on the stage, but it does not add the second copy of the object onto the array. The trace() output goes on like so:
1
1
2
2
3
3
4
4
etc.
I wonder why and I'm really stumped by this.
Here is the code in question:
public class Main extends MovieClip {
public var nicesnowflake: fallingsnow;
var nicesnowflakespawntimer: Timer = new Timer(1000);
public var nicesnowflakearray: Array = new Array();
public function Main() {
nicesnowflakespawntimer.addEventListener(TimerEvent.TIMER, nicesnowflakespawn);
nicesnowflakespawntimer.start();
public function nicesnowflakespawn(event:TimerEvent) : void {
nicesnowflake = new fallingsnow;
nicesnowflake.x = Math.random()* stage.stageWidth;
nicesnowflake.y = - stage.stageHeight + 100;
nicesnowflakearray.push(nicesnowflake);
stage.addChild(nicesnowflake);
trace(nicesnowflakearray.length);
for (var i:Number = 0; i < nicesnowflakearray.length; i++){
nicesnowflakearray[i].addEventListener(Event.ENTER_FRAME, snowhit);
public function snowhit(event:Event) : void {
if (nicesnowflakearray[0].y >= 460){
if (nicesnowflakearray[0].y == stage.stageHeight) {
nicesnowflakearray.splice(nicesnowflakearray.indexOf(nicesnowflake), 1);
//if (this.hitTestObject(nicesnowflake)){
//trace("hit");
I am also fiddling with the collision, but I believe that it would sort itself out when I deal with the array pop and depop properly. However I'm pasting it anyway in case the issue is subtly hidden somewhere I'm not looking for it. And here is the child class:
public class Head extends Main {
public function Head(){
if (false){
super();
this.stop();
So like what happens at the moment is that the array gets populated by the first object that spawns, but there is two objects on the stage, then when the objects reach stage.460y mark the array splices() the one object away and displays an error:
"#1010: A term is undefined and has no properties.
at Main/snowhit()"
then when the next object spawns, it repeats the process. Why does it trace the array.length as "1, 1, 2, 2, 3, 3, 4, 4, 5, 5, etc" until the despawn point and then goes on to display an error and then starts from 1 again, because if the array length is more than one object at the time when the first object of the array gets spliced away, shouldn't it go on as usual, since there are other objects in the array?
Thank you very much to whomever will read this through.There are multiple problems:
1. You should add eventlisteners for your objects only once, but you add eventlisteners every time your timer runs to all of your snowflakes, again and again:
for (var i:Number = 0; i < nicesnowflakearray.length; i++){
nicesnowflakearray[i].addEventListener(Event.ENTER_FRAME, snowhit);
change it to
nicesnowflake.addEventListener(Event.ENTER_FRAME, snowhit);
I don`t see why its even necessary to employ this snowflakearray, it would be much straight forward if you simply let the snowflakes take care of themselves.
2. Then you have to change your enterframe function accordingly
public function snowhit(event:Event) : void {
if (e.currentTarget.y >= 460){
if (e.currentTarget.y == stage.stageHeight) {
e.currentTarget.removeEventlistener(Event.ENTER_FRAME, snowhit);
removeChild(e.currentTarget);
3.
//if (this.hitTestObject(nicesnowflake)){
//trace("hit");
since "this" is a reference to the Main class (root) it surely won`t function as you intend it to.
if (false){
super();
makes no sense to use a condition that can never be true -
Question with object arrays..
This is my code and it doesn't seem to be working properly
public class familymember {
public familymember(){
Object[] array=new Object[500];
public static void main(String args[]) {
familymember array2 = new familymember();
array2.array[51] = "500";
System.out.println( array2.array[51]);
I get the error message
Error : No variable array defined in class familymember.
familymember.java line 15 array2.array[51] = "500";
What am i doing wrong?array cannot be accessed from outside it's block (in this case the constructor).
just change your code this way:
public class familymember {
private Object[] array; // or public or protected or whatever you want
public familymember(){
array=new Object[500];
public static void main(String args[]) {
familymember array2 = new familymember();
array2.array[51] = "500";
System.out.println( array2.array[51]);
} -
I need help with a Object Array
I am having trouble and this maybe really simple seeing that I am fairly new to java but I have text that is being broken down in to preset part with those parts stored in Object arrays.
Now I also have a object array inside my object array. Within the second object array are the broken down parts of the text and I want to compare this text with another string so for example this is what I am trying
boolean found = false;
for (int i = 0; i < FirstObjectArray.length ;i++)
Object[] SecondObjectArray = (Object[]) FirstObjectArray;
if(SecondObjectArray[0] == "string")
found = true;
break;
else
found = false;
}Help would be very appreciated.astlanda wrote:
Sure, you're right.
[public boolean equals(Object obj)|http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#equals%28java.lang.Object%29]
sharkura said all the OP needs at the moment. I just wanted to clarify a bit why You don't use == 99.999% of the time with objects, and never with String.
I have argued elsewhere in these forums that it is inappropriate to tell anyone that you never use == to compare objects. This has not always been accepted. I have, on rare occasions, known experienced developers to blindly compare two objects with equals(), and cite the professor that taught them, 15 years iin the past, that object references are never compared using ==, but always with equals().
However, the cases where == is appropriate and equals() is not are indeed rare, but not, in my experience, non-existent. In my statement, I probably exaggerated. And String is a case where I can probably accept that you will probably never go wrong with equals(). If the String has been pooled (see String::intern()), you can actually use either. From the javadocs: "*It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.*"
¦ {Þ -
Table with object array data provider
hi!
i use the studio creator table and want to fill it with an object array data provider!
i have an array and the getter:
public TanData[] getTanDataArray()
return tanDataArray;
}i choosed this for the data provider and in table layout i choose the dataprovider, but when i run my application there are no datas found although the array isn't empty!maybe this is a problem:
i got my data from a database table and i store it in a vector.
in the example they have a class WeekBean and they fill their array with
WeekBean[] weeks = {
new WeekBean(1),
new WeekBean(2),
new WeekBean(3),
new WeekBean(4)
};and i tried to do this:
private Vector<TanData> tanDataList = new Vector();
private TanData[] tanDataArray;
getTanDataList().copyInto(tanDataArray);could it be that that isn't correct? -
How to initialize the array with object?
Here is type I have.
CREATE OR REPLACE TYPE SYSADM.AP_COMMENT_TYPE AS OBJECT
BU_AP VARCHAR2(5),
VOUCHER VARCHAR2(10),
V_LINE INTEGER,
USERID VARCHAR2(20),
COMMENT_DTTM DATE,
COMMENT VARCHAR2(254)
CREATE OR REPLACE TYPE SYSADM.AP_COMMENT_COLL AS VARRAY(1000) OF SYSADM.AP_COMMENT_TYPE;
Then I created a procedure to grab some data.
PROCEDURE get_voucher_comments (
v_bu_in IN VARCHAR2,
v_voucher_in IN VARCHAR2,
v_line_in IN NUMBER,
v_userid IN VARCHAR2,
voucher_comment OUT sysadm.ap_comment_coll
IS
i NUMBER := 1;
v_comments VARCHAR2 (254) := ' ';
comment_type sysadm.ap_comment_type;
v_line_num NUMBER := 0;
CURSOR get_all_comment
IS
SELECT voucher_line_num, descr254_mixed
FROM ps_fas_ap_comment
WHERE business_unit = voucher_comment (i).bu_ap
AND voucher_id = voucher_comment (i).voucher;
CURSOR get_line_comment
IS
SELECT descr254_mixed
FROM ps_fas_ap_comment
WHERE business_unit = voucher_comment (i).bu_ap
AND voucher_id = voucher_comment (i).voucher
AND voucher_line_num = voucher_comment (i).v_line;
BEGIN
voucher_comment (1) := ap_comment_type (' ', ' ', 0, ' ', '', ' ');
--voucher_comment (1) := ap_comment_type (null, null, null, null, null,null);
IF voucher_comment (i).v_line = 0
THEN
OPEN get_all_comment;
LOOP
FETCH get_all_comment
INTO v_line_num, v_comments;
voucher_comment.EXTEND;
voucher_comment (i) :=
ap_comment_type (v_bu_in,
v_voucher_in,
v_line_num,
v_userid,
TO_DATE (TO_CHAR (SYSDATE,
'DD-MON-YYYY HH24:MI:SS'
'DD-MON-YYYY HH24:MI:SS'
v_comments
i := i + 1;
END LOOP;
ELSE
OPEN get_line_comment;
LOOP
FETCH get_line_comment
INTO v_comments;
voucher_comment.EXTEND;
voucher_comment (i) :=
ap_comment_type (v_bu_in,
v_voucher_in,
v_line_num,
v_userid,
TO_DATE (TO_CHAR (SYSDATE,
'DD-MON-YYYY HH24:MI:SS'
'DD-MON-YYYY HH24:MI:SS'
v_comments
i := i + 1;
END LOOP;
END IF;
END get_voucher_comments;
But when I tried to test the procedure, got error: ORA-06531: Reference to uninitialized collection. Does anyone have experience of handling array with object?
declare
O_voucher_comment SYSADM.AP_COMMENT_COLL;
begin
FAS_AP_EXCEPTIONS.GET_VOUCHER_COMMENTS('FCCAN', '20494753', 1, 'KEHE', O_voucher_comment);
end;Thanks for that. I changed it a little bit, but when i ran this script, got ORA-06532: Subscript outside of limit.
declare
O_voucher_comment SYSADM.AP_COMMENT_COLL := sysadm.ap_comment_coll(null);
begin
FAS_AP_EXCEPTIONS.GET_VOUCHER_COMMENTS('FCCAN', '20494753', 0, 'KEHE', O_voucher_comment);
end;
PROCEDURE get_voucher_comments (
v_bu_in IN VARCHAR2,
v_voucher_in IN VARCHAR2,
v_line_in IN NUMBER,
v_userid IN VARCHAR2,
voucher_comment OUT sysadm.ap_comment_coll
IS
i NUMBER := 1;
v_comments VARCHAR2 (254) := ' ';
comment_type sysadm.ap_comment_type;
v_line_num NUMBER := 0;
CURSOR get_all_comment
IS
SELECT voucher_line_num, descr254_mixed FROM ps_fas_ap_comment
WHERE business_unit = v_bu_in AND voucher_id = v_voucher_in;
CURSOR get_line_comment
IS
SELECT descr254_mixed FROM ps_fas_ap_comment
WHERE business_unit = v_bu_in AND voucher_id = v_voucher_in
AND voucher_line_num = v_line_in;
BEGIN
--voucher_comment() := SYSADM.ap_comment_type (NULL, NULL, NULL, NULL, NULL, NULL);
--' ', ' ', 0, ' ', '', ' ' sysadm.ap_comment_coll
voucher_comment := sysadm.ap_comment_coll(null);
IF v_line_in = 0
THEN
OPEN get_all_comment;
LOOP
FETCH get_all_comment
INTO v_line_num, v_comments;
if i > 1
then
voucher_comment.EXTEND;
end if;
voucher_comment (i) := ap_comment_type (v_bu_in,
v_voucher_in, v_line_num, v_userid,
TO_DATE (TO_CHAR (SYSDATE, 'DD-MON-YYYY HH24:MI:SS'), 'DD-MON-YYYY HH24:MI:SS'), v_comments );
i := i + 1;
END LOOP;
ELSE
OPEN get_line_comment;
LOOP
FETCH get_line_comment
INTO v_comments;
voucher_comment.extend(6);
voucher_comment (i) := ap_comment_type (v_bu_in, v_voucher_in, v_line_num, v_userid, TO_DATE (TO_CHAR (SYSDATE, 'DD-MON-YYYY HH24:MI:SS' ), 'DD-MON-YYYY HH24:MI:SS'), v_comments);
i := i + 1;
END LOOP;
END IF;
END get_voucher_comments; -
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. -
Object Array problem in Websphere WebServices
Hi,
Can someone help me out with a situation that I am stuck with in WebServices.
I have a WebService which returns a DTO which has a getter and setter for an array of another type of DTO object.
Sample:-
public class MyDTO extends AnotherDTO implements Serializable {
private InnerDTO qcDtoList[] = new InnerDTO[0];
public MyDTO() {
public InnerDTO[] getQcDtoList() {
return qcDtoList;
public void setQcDtoList(InnerDTO[] resEDXDTOs) {
qcDtoList = resEDXDTOs;
But when I generate the WSDL for the webservice using WSAD 5.1 that uses the above DTO, the server side generated skeleton file looks like:-
public class MyDTO extends AnotherDTO implements java.io.Serializable {
private InnerDTO[] qcDtoList;
public MyDTO() {
public InnerDTO[] getQcDtoList() {
return qcDtoList;
public void setQcDtoList(InnerDTO[] qcDtoList) {
this.qcDtoList = qcDtoList;
As you can see from above, my initialization info is not available in the generated skeleton. I also tried putting the initialization in the constructor, with no effect.
What could be the reason for this? And is it possible to initialize my InnerDTO without losing it in the generated skeleton?
I simply want to initialize the object array.
If I need to modify my WSDL, what additional annotations should I add on the WSDL to get the desired effect?
I use WSAD's (Websphere Studio App Developer) IBM Websphere Webservices protocol and the JDK version is 1.3.1 and WSAD version is 5.1.
I would really appreciate if you can throw light on this?
Thanx and Regds,
Prashanth.Thank you for the quick response. I looked at the example you suggested and made the following changes. Now I'm receiving an "Invalid datatype" error on the "SELECT column_value FROM TABLE(CAST(tbl_cat AS tbl_integer))" statement. I must be missing something simple and I just can't put my finger on it.
PROCEDURE SEL_SEARCH_RESULTS (v_term IN VARCHAR2,
v_categories IN ARCHIVE.integer_aat,
rs OUT RSType)
AS
/* PURPOSE: Return Search Results for the Category and Keyword Provided
VARIABLES:
v_categories = Document Categories array entered
v_term = Keyword entered
rs = Result Set
TYPE tbl_integer IS TABLE OF INTEGER;
tbl_cat tbl_integer;
BEGIN
FOR i IN 1 .. v_categories.COUNT
LOOP
tbl_cat.EXTEND(1);
tbl_cat(i) := v_categories(i);
END LOOP;
OPEN rs FOR
SELECT A.ID,
B.CATEGORY,
A.FILENAME,
A.DISPLAY_NAME,
A.COMMENTS
FROM TBL_ARCHIVE_DOCUMENTS A,
TBL_ARCHIVE_DOC_CAT B,
TBL_ARCHIVE_DOC_KEYWORDS C
WHERE A.ID = B.ID
AND A.ID = C.ID
AND B.CATEGORY IN (SELECT column_value FROM TABLE(CAST(tbl_cat AS tbl_integer)))
AND C.KEYWORD = v_term
ORDER BY A.ID;
END SEL_SEARCH_RESULTS; -
Multi-dimensional arrays with non-specified dimension
Hi all,
I'm trying to write a method to create a multi-dimensional array of
Integer, based on another one, taken as parameter. I would like the
method to work for an array of a non-specified dimension, that is,
it could take as parameter a Integer[], or a Integer[][], or a
Integer[][][] and so on.
The idea is to have as a result an array with the original elements
doubled.
Here is my recursive function:
public static Object[] f(Object[] a) {
// the array to be returned is created with the
// same size as the original
Object[] r = new Object[a.length];
for (int i=0; i<a.length; i++) {
Object elem = a;
Object newElem = null;
if (elem instanceof Object[]) {
// Recursive case
newElem = f((Object[]) elem);
} else if (elem instanceof Integer) {
// Base case
newElem = new Integer(((Integer)elem).intValue() * 2);
r[i] = newElem;
return r;
This method returns an array with the same structure (that is, same
dimensions) of the array taken in the constructor. In the recursive
case, it just calls the function to the inner arrays. In the base
case, where I have an Integer, it creates a new Integer, whose
value is the old multiplied by 2.
Then I initialize an array:
public static void main(String args[]) throws Exception {
Integer[][] a = new Integer[][] {
new Integer[] {
new Integer(0), new Integer(2)
new Integer[] {
new Integer(1), new Integer(4), new Integer(3)
// And try to call the function like this:
Integer [][] b = (Integer [][]) f(a);
} And I get a java.lang.ClassCastException: [Ljava.lang.Object;
I don't understand the reason of this exception, because the
object returned is a Integer[][]. Isn't it?
And since I don't have a compiler error in the cast, that means
that Object[] and Integer[][] are not inconvertible. Right?
Could anyone explain me why this is wrong and/or give me some
ideas to do what I'm trying to do?
Thanks a lot,
AngelaI retract my previous statement about using
reflection. Use "Object[] r =(Object[])a.clone()"
to create a new array of the same type.You don't need temporary array variable here.
You could simply use argument a instead of r.
(But this my gotcha is derived from your clever rep.)Well, this isn't a temporary variable, its the return variable, which is different. If you don't want the original matrix changed, you have to clone the argument. -
I have too many books and not enough understanding on this subject.
I am trying to fill an object type array with values and am totally confused. In my application, I successfully create a constructor in one file and test the object with some values in another file. I have two objects for employee and would like to place the object values into an object array. There is plenty of information on int[] arrays, but little on object arrays.
After I can do the array fill:
I would like to provide object values with JOptionPane.
Change the print display to show all array elements
But one thing at a time.
I was thinking that objects exist first, then are loaded or filled into an object array. I seem to misunderstand as I am not performing the array fill very well. Following a book example seems to confuse me only more.
Thank you
//emp.java
import java.util.*;
public class Emp {
private int id;
private String name;
private double salary;
public Emp(int ident, String nm, double sal) {
id = ident;
name = nm;
salary = sal;
// method raise salary by 5 percent
double raise() { return salary * 1.05;} // ends raise method
// setters and getters
public String getName() { return(name); }
public double getSalary() { return(salary); }
public int getID() { return(id); }
public void setName(String nm) { name = nm; }
public void setSalary(double sal) { salary = sal; }
public void setID(int ident) { id = ident; }
}The test file
//EmpTest.java
import javax.swing.JOptionPane;
public class EmpTest {
public static void main(String[] args_) {
// Create object based on EmployeeTest2 class
// to add employee data to the array called empArray
Emp emp1 = new Emp(1,"Smith",2000);
Emp emp2 = new Emp(2,"Jones",2500);
//test and confirm the objects emp1 and emp2
int i;
String n;
double s;
double newsal;
// get the salary after the 5 percent raise
i = emp1.getID();
n = emp1.getName();
s = emp1.getSalary();
newsal = emp1.raise();
System.out.println("object Employee 1 ID: " + i + " Name: " + n + " Old Salary: " + s + " New salary: " + newsal);
i = emp2.getID();
n = emp2.getName();
s = emp2.getSalary();
newsal = emp2.raise();
System.out.println("object Employee 2 ID: " + i + " Name: " + n + " Old Salary: " + s + " New salary: " + newsal);
// get the number of employees with JOptionPane
String employeeCountString = JOptionPane.showInputDialog(
"Employee Database " +
"\nEnter the number of employees: ");
// convert into an integer empcount
int employeeCount = Integer.parseInt(employeeCountString);
// initialize the empArray.
Employee2[] empArray = new Employee2[employeeCount];
fill(empArray);
printContents(empArray);
} //end main method
private static void fill(Object[] my_arr) {
int i;
for (i = 0; i < my_arr.length; i = i + 1) {
// get the name from the keyboard
String employeeName = JOptionPane.showInputDialog(
"Enter the employee name: ");
// do something here to set the array element to employeeName
// get the salary
String employeeSalaryString = JOptionPane.showInputDialog(
"Enter the employee monthly salary: ");
//convert into a double
double employeeSalary = Double.parseDouble(employeeSalaryString);
//do something here to set array for salary
my_arr[i] = new Employee2(1,"S1",5); // temporary values here
} //ends for loop
} // ends method
private static void printContents(Object[] the_arr) {
int i;
for (i = 0; i < the_arr.length; i = i + 1) {
System.out.print("Element: " + i);
//System.out.println(" has the value : " + the_arr);
System.out.println(" has the value : " + i);
} //ends for loop
} // ends printContents method
} // ends EmpTest classwhat's the matter ?
Try this :
import javax.swing.JOptionPane;
public class EmpTest {
public static void main(String[] args_) {
// Create object based on EmployeeTest2 class
// to add employee data to the array called empArray
Emp emp1 = new Emp(1, "Smith", 2000);
Emp emp2 = new Emp(2, "Jones", 2500);
// test and confirm the objects emp1 and emp2
int i;
String n;
double s;
double newsal;
// get the salary after the 5 percent raise
i = emp1.getID();
n = emp1.getName();
s = emp1.getSalary();
newsal = emp1.raise();
System.out.println("object Employee 1 ID: " + i + " Name: " + n + " Old Salary: " + s + " New salary: "
+ newsal);
i = emp2.getID();
n = emp2.getName();
s = emp2.getSalary();
newsal = emp2.raise();
System.out.println("object Employee 2 ID: " + i + " Name: " + n + " Old Salary: " + s + " New salary: "
+ newsal);
// get the number of employees with JOptionPane
String employeeCountString = JOptionPane.showInputDialog("Employee Database "
+ "\nEnter the number of employees: ");
// convert into an integer empcount
int employeeCount = Integer.parseInt(employeeCountString);
// initialize the empArray.
Emp[] empArray = new Emp[employeeCount];
fill(empArray);
printContents(empArray);
} // end main method
private static void fill(Object[] my_arr) {
int i;
for (i = 0; i < my_arr.length; i = i + 1) {
// get the name from the keyboard
String employeeName = JOptionPane.showInputDialog("Enter the employee name: ");
// do something here to set the array element to employeeName
// get the salary
String employeeSalaryString = JOptionPane.showInputDialog("Enter the employee monthly salary: ");
// convert into a double
double employeeSalary = Double.parseDouble(employeeSalaryString);
// do something here to set array for salary
my_arr[i] = new Emp(1, employeeName, employeeSalary); // temporary values here
} // ends for loop
} // ends method
private static void printContents(Object[] the_arr) {
int i;
for (i = 0; i < the_arr.length; i++) {
System.out.print("Element # "+i+" Name= "+ ((Emp)the_arr).getName());
System.out.print("Salary # "+i+" Salary = "+ ((Emp)the_arr[i]).getSalary());
} // ends for loop
} // ends printContents method
} // ends EmpTest class -
Trying to build (simple) color palette, but keep getting ArrayIndexOutOfBoundsException: 0 when trying to fill the array with Hue values (Saturation and Brightness remain 100%):
private Color[] hsb = new Color[numberOfCircles];
float h=0;
float raise=(1.f/numberOfCircles);
for (int i=0; i<stKrogcev; i++) {
hsb=Color.getHSBColor(h,1.0f,1.0f); //getHSBColor: "Creates a Color object based on the specified values for the HSB color model."
h+=raise;
}What am I doing wrong?
What other way could you fill array (Color, int, float, ...) with Hue values?
This is what I have thus far (only colors missing; not sure whether Sun supports images): [http://www.shrani.si/f/1G/uM/v29MKIC/palette.jpg]. First three columns in the right-hand table are awaiting RGB values respectively, the last column gets Hue value.pbrockway2, numberOfCircles (or stKrogcev ) is an int, and is NOT zero. That Color[] hsb is zero.
import javax.swing.*;
import java.awt.*;
public class BarvnaPaleta {
public static void main (String[] args) {
System.out.print("Stevilo krogcev: ");
int n = BranjePodatkov.preberiInt(); // BranjePodatkov: just some custom class for reading input
Okno o = new Okno(n);
o.setVisible(true);
class Okno extends JFrame {
RisalnaPlosca risalna;
public Okno(int n) {
setTitle("Barvna Paleta");
setSize(1200,900);
setLocation(0,0);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
risalna = new RisalnaPlosca(n);
add(risalna);
class RisalnaPlosca extends JPanel {
private final int ROB = 300;
int stKrogcev;
private int izhX, izhY;
private int r1;
private int sirina = 60;
private int visina = 20;
private double x, y, r2, r3;
private double vmesniKot;
private double polovicaVmesnegaKota;
//the much needed color arrays
public Color[] hsb = new Color[stKrogcev];
private String[] red = new String[stKrogcev];
private String[] green = new String[stKrogcev];
private String[] blue = new String[stKrogcev];
public RisalnaPlosca(int n) { //constructor
stKrogcev = n;
setBackground(Color.white);
public void paintComponent(Graphics g) {
super.paintComponent(g);
izhX = getWidth()/2 -r1;
izhY = getHeight()/2 -r1;
vmesniKot=(2*Math.PI/stKrogcev);
polovicaVmesnegaKota=(vmesniKot)/2;
r1=getHeight();
r3=(r1*Math.sin(polovicaVmesnegaKota))/(1+Math.sin(polovicaVmesnegaKota));
r2=r1-r3;
narisiKrog(g);
napolniHSB(g); // LINE 53
narisiKrogce(g);
private void narisiKrog(Graphics g) { //draw the BIG Circle
g.setColor(Color.BLACK);
g.drawOval(0, 0, r1, r1);
private void narisiKrogce(Graphics g) { //draw small circles (as many as user wants, max. is 256 of Hue values!
for(int i=0; i<stKrogcev; i++) {
x=(r2/2)*(Math.cos(vmesniKot*i)+1);
y=(r2/2)*(Math.sin(vmesniKot*i)+1);
//can't use below two because of the "fillHSB"=="napolniHSB" method not working
//Color c = new Color(Integer.parseInt(red),Integer.parseInt(green[i]),Integer.parseInt(blue[i]));
//g.setColor(c);
g.drawOval((int)x, (int)y, (int)r3, (int)r3);
narisiLegendo((int)x,(int)y, i, g); //draw a legend (last method)
private void napolniHSB(Graphics g) { //fillHSB method
float h=0, raise=1.0f/stKrogcev;
for (int i=0; i<stKrogcev; i++) {
hsb[i]=Color.getHSBColor(h,1.0f,1.0f); // LINE 75
red[i]=Integer.toString(hsb[i].getRed()); // this and below two for converting HSB/HSL into RGB
green[i]=Integer.toString(hsb[i].getGreen());
blue[i]=Integer.toString(hsb[i].getBlue());
h+=raise;
private void narisiLegendo(int x, int y, int i, Graphics g) { //draw a legend, i.e. 4 right columns
//can't use drawString as there are no color arrays (yet)
g.drawLine((int)(x+r3/2),(int)(y+r3/2),getWidth()-ROB,(visina+i*visina)+visina/2);
g.drawRect(getWidth()-ROB, (visina+i*visina), sirina, visina); //Red
//g.drawString(red[i], getWidth()-ROB, (visina+i*visina));
g.drawRect(getWidth()-ROB+sirina, (visina+i*visina), sirina, visina); //Green
//g.drawString(green[i], getWidth()-ROB, (visina+i*visina));
g.drawRect(getWidth()-ROB+2*sirina, (visina+i*visina), sirina, visina); //Blue
//g.drawString(blue[i], getWidth()-ROB, (visina+i*visina));
g.drawRect(getWidth()-ROB+3*sirina, (visina+i*visina), sirina, visina); //Hue
//g.drawString(, getWidth()-ROB, (visina+i*visina)); -
Saving An Object Array to a File
Please Help,
I am fairly new to Java. I am trying to write a program that inputs merchandise information (ItemName, Description, Price, etc�) to an object array. The program works internally with the array perfectly, but I can�t get it to save the array to a file so it can be read and reused the next time the program is run. The class the array is built on implements Serializable, but when it tries to save it to a file, it throws an exception message saying that my object is not serializable.
Does anyone have some code to help me save information to an array (so it can be used within the program), save the array to a disk file, and read the file back into the program the next time the program opens?
Thank you,
BobThank you for your help. The total code is quite lengthy so I�ve tried to pick the most relevant code to include here.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.text.*;
import java.io.*;
public class Class1 extends WindowAdapter implements ActionListener
// Object Array Declaration.
ItemInfo ItemArray[] = new ItemInfo[100];
* This is the Inner Class that the Array is built on. I have two constructors in it because I
* tried several different methods to make this write to the disk file
public class ItemInfo implements Serializable
int ItemNum;
int DeptNum;
String ItemName;
String Model;
String Description;
float Price;
int Units;
// Constructors
public ItemInfo() {};
public ItemInfo(int inItemNum, int inDeptNum, String
inItemName, String inModel, String
inDescription, float inPrice, int inUnits)
ItemNum = inItemNum;
DeptNum = inDeptNum;
ItemName = inItemName;
Model = inModel;
Description = inDescription;
Price = inPrice;
Units = inUnits;
} // end class ItemInfo.
* openOutputStream() *
private void openOutputStream()
try
// create file and output object streams
outputItemFile = new FileOutputStream("A:ItemFile.txt");
objSaveItems = new ObjectOutputStream(outputItemFile);
} // end try
catch (Exception error)
System.err.println("Error opening file");
} // end catch
} // end openOutputStream().
* closeOutputStream() *
private void closeOutputStream()
try
objSaveItems.close();
outputItemFile.close();
catch (IOException error)
System.err.println("Error Closing File");
} // end catch
} // end closeOutputStream().
* AddToItemArray() - This method just assigns the information to the Array elements *
private void AddToItemArray()
int ArrayNum = intItemFileSize - 1;
ItemArray[ArrayNum] = new ItemInfo();
ItemArray[ArrayNum].ItemNum = intNewItemNum;
ItemArray[ArrayNum].DeptNum = intDeptNum;
ItemArray[ArrayNum].ItemName = strItemName;
ItemArray[ArrayNum].Model = strModel;
ItemArray[ArrayNum].Description = strDescription;
ItemArray[ArrayNum].Price = fltPrice;
ItemArray[ArrayNum].Units = intUnits;
} // end AddToItemArray().
* WriteToFile() - This is the latest effort to write to the file. The file gets opened, and
* the first element gets printed, but after that nothing but error messages (printed * below).
private void WriteToFile()
try
openOutputStream();
for (int a = 0; a <= intItemFileSize; a++)
objSaveItems.writeObject(ItemArray[a]);
objSaveItems.flush();
closeOutputStream();
} // end try.
catch (Exception error)
System.err.println("Error writing to file");
} // end WriteToFile().
This is what appears on the disk file after I run the program (three items entered):
� sr Class1$ItemInfo�&q����B I DeptNumI ItemNumF PriceI UnitsL
Descriptiont Ljava/lang/String;L ItemNamet Ljava/lang/String;L Modelt Ljava/lang/String;L this$0t LClass1;xp A��� t
Claw Hammert Hammert CL550{sr java.io.NotSerializableException(Vx �� 5 xr java.io.ObjectStreamExceptiond��k�9�� xr java.io.IOExceptionl�sde%�� xr java.lang.Exception��> ; � xr java.lang.Throwable��5'9w�� L
detailMessaget Ljava/lang/String;xpt Class1
Maybe you are looking for
-
Not able to import the article with sidecar.xml
Hi, With the new DPS version (ver. 18), we are not able to import the article with sidecar.xml. Could you please check and suggest the solution for the same. With Regards, Anil Yadav
-
SYS PACKAGE DBMS_DEFER_IMPORT_INTERNAL NOT ACCESSIBLE
We are trying to import a dmp file to Oracle 10.2.0.1 database. This is a full import and ignore=y has been given. We found the following error for one particular user ORA-06550: line 2, column 5: PLS-00302: component 'DBMS_DEFER_IMPORT_INTERNAL' mus
-
I put a CD into Itunes to burn it and when it brought up no track names I realsied I had lost my connection. So took the CD out, reconnected, made sure the right box was ticked in preferences and tried again. Nothing. It's like it's 'remembering' the
-
is there any other way to unlock an I phone?
-
Hi all, I am new to database back up. Can anyone explain me what is the difference between the back up which is taken using db13 in sap and taking back up directly from sql enterprise server in windows. Is it possible to do offline and online back up