Array of an Object
I hope this is the right place to post this but here goes. I am trying to create an array of an object which I have created to store basic details of various people, I have declared the array like this people[] Person = new people[5]; //people is the name of the object but whenever i try to assign values to one of objects, for example Person[number].setName(textName.getText()); //number is predetermined array value to use it throws a null pointer exception. If I define a single instance such as people Person = new people(); it works fine but I specifically need and array. Any help would be greatly appreciated.
I have to say thanks again, it is working now, all that's left is to change is the naming conventions <img class="emoticon" src="images/emoticons/happy.gif" border="0" alt="" />.
Similar Messages
-
I can't seem to get individual elements when comparing 2 arrays using Compare-Object
My backup software keeps track of servers with issues using a 30 day rolling log, which it emails to me once a week in CSV format. What I want to do is create a master list of servers, then compare that master list against the new weekly lists to identify
servers that are not in the master list, and vice versa. That way I know what servers are new problem and which ones are pre-existing and which ones dropped off the master list. At the bottom is the entire code for the project. I know it's a bit much
but I want to provide all the information, hopefully making it easier for you to help me :)
Right now the part I am working on is in the Compare-NewAgainstMaster function, beginning on line 93. After putting one more (fake) server in the master file, the output I get looks like this
Total entries (arrMasterServers): 245
Total entries (arrNewServers): 244
Comparing new against master
There are 1 differences.
InputObject SideIndicator
@{Agent= Virtual Server in vCenterServer; Backupse... <=
What I am trying to get is just the name of the server, which should be $arrDifferent[0] or possibly $arrDifferent.Client. Once I have the name(s) of the servers that are different, then I can do stuff with that. So either I am not accessing the array
right, building the array right, or using Compare-Object correctly.
Thank you!
Sample opening lines from the report
" CommCells > myComCellServer (Reports) >"
" myComCellServer -"
" 30 day SLA"
CommCell Details
" Client"," Agent"," Instance"," Backupset"," Subclient"," Reason"," Last Job Id"," Last Job End"," Last Job Status"
" myServerA"," vCenterServer"," VMware"," defaultBackupSet"," default"," No Job within SLA Period"," 496223"," Nov 17, 2014"," Killed"
" myServerB"," Oracle Database"," myDataBase"," default"," default"," No Job within SLA Period"," 0"," N/A"," N/A"
Entire script
# things to add
# what date was server entered in list
# how many days has server been on list
# add temp.status = pre-existing, new, removed from list
# copy sla_master before making changes. Copy to archive folder, automate rolling 90 days?
## 20150114 Created script ##
#declare global variables
$global:arrNewServers = @()
$global:arrMasterServers = @()
$global:countNewServers = 1
function Get-NewServers
Param($path)
Write-Host "Since we're skipping the 1st 6 lines, create test to check for opening lines of report from CommVault."
write-host "If not original report, break out of script"
Write-Host ""
#skip 5 to include headers, 6 for no headers
(Get-Content -path $path | Select-Object -Skip 6) | Set-Content $path
$sourceNewServers = get-content -path $path
$global:countNewServers = 1
foreach ($line in $sourceNewServers)
#declare array to hold object temporarily
$temp = @{}
$tempLine = $line.Split(",")
#get and assign values
$temp.Client = $tempLine[0].Substring(2, $tempLine[0].Length-3)
$temp.Agent = $tempLine[1].Substring(2, $tempLine[1].Length-3)
$temp.Backupset = $tempLine[3].Substring(2, $tempLine[3].Length-3)
$temp.Reason = $tempLine[5].Substring(2, $tempLine[5].Length-3)
#write temp object to array
$global:arrNewServers += New-Object -TypeName psobject -Property $temp
#increment counter
$global:countNewServers ++
Write-Host ""
$exportYN = Read-Host "Do you want to export new servers to new master list?"
$exportYN = $exportYN.ToUpper()
if ($exportYN -eq "Y")
$exportPath = Read-Host "Enter full path to export to"
Write-Host "Exporting to $($exportPath)"
foreach ($server in $arrNewServers)
$newtext = $Server.Client + ", " + $Server.Agent + ", " + $Server.Backupset + ", " + $Server.Reason
Add-Content -Path $exportPath -Value $newtext
function Get-MasterServers
Param($path)
$sourceMaster = get-content -path $path
$global:countMasterServers = 1
foreach ($line in $sourceMaster)
#declare array to hold object temporarily
$temp = @{}
$tempLine = $line.Split(",")
#get and assign values
$temp.Client = $tempLine[0]
$temp.Agent = $tempLine[1]
$temp.Backupset = $tempLine[2]
$temp.Reason = $tempLine[3]
#write temp object to array
$global:arrMasterServers += New-Object -TypeName psobject -Property $temp
#increment counter
$global:countMasterServers ++
function Compare-NewAgainstMaster
Write-Host "Total entries (arrMasterServers): $($countMasterServers)"
Write-Host "Total entries (arrNewServers): $($countNewServers)"
Write-Host "Comparing new against master"
#Compare-Object $arrMasterServers $arrNewServers
$arrDifferent = @(Compare-Object $arrMasterServers $arrNewServers)
Write-Host "There are $($arrDifferent.Count) differences."
foreach ($item in $arrDifferent)
$item
## BEGIN CODE ##
cls
$getMasterServersYN = Read-Host "Do you want to get master servers?"
$getMasterServersYN = $getMasterServersYN.ToUpper()
if ($getMasterServersYN -eq "Y")
$filePathMaster = Read-Host "Enter full path and file name to master server list"
$temp = Test-Path $filePathMaster
if ($temp -eq $false)
Read-Host "File not found ($($filePathMaster)), press any key to exit script"
exit
Get-MasterServers -path $filePathMaster
$getNewServersYN = Read-Host "Do you want to get new servers?"
$getNewServersYN = $getNewServersYN.ToUpper()
if ($getNewServersYN -eq "Y")
$filePathNewServers = Read-Host "Enter full path and file name to new server list"
$temp = Test-Path $filePathNewServers
if ($temp -eq $false)
Read-Host "File not found ($($filePath)), press any key to exit script"
exit
Get-NewServers -path $filePathNewServers
#$global:arrNewServers | format-table client, agent, backupset, reason -AutoSize
#Write-Host ""
#Write-Host "Total entries (arrNewServers): $($countNewServers)"
#Write-Host ""
#$global:arrMasterServers | format-table client, agent, backupset, reason -AutoSize
#Write-Host ""
#Write-Host "Total entries (arrMasterServers): $($countMasterServers)"
#Write-Host ""
Compare-NewAgainstMasterdo not do this:
$arrDifferent = @(Compare-Object $arrMasterServers $arrNewServers)
Try this:
$arrDifferent = Compare-Object $arrMasterServers $arrNewServers -PassThru
¯\_(ツ)_/¯
This is what made the difference. I guess you don't have to declare arrDifferent as an array, it is automatically created as an array when Compare-Object runs and fills it with the results of the compare operation. I'll look at that "pass thru" option
in a little more detail. Thank you very much!
Yes - this is the way PowerShell works. You do not need to write so much code once you understand what PS can and is doing.
¯\_(ツ)_/¯ -
How to pass Array of Java objects to Callable statement
Hi ,
I need to know how can I pass an array of objects to PL/SQL stored procedure using callable statement.
So I am having and array list of some object say xyz which has two attributes string and double type.
Now I need to pass this to a PL/SQL Procedure as IN parameter.
Now I have gone through some documentation for the same and found that we can use ArrayDescriptor tp create array (java.sql.ARRAY).
And we will use a record type from SQL to map this to our array of java objects.
So my question is how this mapping of java object's two attribute will be done to the TYPE in SQL? can we also pass this array as a package Table?
Please help
ThanksI seem to remember that that is in one of Oracle's online sample programs.
http://www.oracle.com/technology/sample_code/tech/java/sqlj_jdbc/index.html -
I was wondering how would you declare an array of class objects. Here is my situation:
I'm working on a project dealing with bank accounts. Each customer has a specific ID and a balance. I have to handle transactions for each customer at different times, so I was thinking that I need an array of class objects; however, I dont know how to initialize them.
Here's what I did:
BankAccount [ ] myAccount = new BankAccount[10];
// 10 = 10 customers
How do I initialize the objects?
ThankzI was wondering how would you declare an array of
class objects. Here is my situation:
I'm working on a project dealing with bank accounts.
Each customer has a specific ID and a balance. I have
to handle transactions for each customer at different
times, so I was thinking that I need an array of
class objects; however, I dont know how to initialize
them.
Here's what I did:
BankAccount [ ] myAccount = new BankAccount[10];
// 10 = 10 customers
How do I initialize the objects?
Thankz
HAI
Use the hashtable
and store the classObject of each customer with the corresponding Id in it
and whenever u want to recover a class match the Id and get the corresponding class
that is the best way to solve ur problem
Regards
kamal -
How to decide if Object is an array or single object
Hi ,
I have a function which can return an Array of objects or a single Object...how can I decided what function has returned to me.?...
I am looking for some way by which I can decided if it is an Array or a Object....
ThanksHow about:
yourObject.getClass().isArray(); // returns boolean -
How to create an array of an object,
Hi,
Trying this in Oracle 10.3 studio, I have to use a web service, I have re-catalogued the web service succesfully,
I am getting compilation error whenI try to create an array of a object,
Services.PackageTrackingService.PackageTrackingItem[] pkgTrackingItem = new Services.PackageTrackingService.PackageTrackingItem[2];
I am giving the array size as 2,
The comilation error is showing as
Multiple markers at this line
- statement is expected
- Expecting ';' but 'pkgTrackingItem' was found
- expression is expected
Is there any other way to create the array?
Thanks in advance.
-SreeHi,
Please declare the array in following manner.
Services.PackageTrackingService.PackageTrackingItem[] pkgTrackingItem;
Now you can insert the element into the array by pkgTrackingItem[0], pkgTrackingItem[1] etc.
Bibhu -
I just picked up coldfusion about a month ago, so my
coldfusion lingo sucks. I have been programming in C++ for over 5
years now and will be using a lot of C++ terminology to help avoid
any confusion. I am writing a cfc function that preforms web
servicing. This function needs to return an object/class that is
defined in another coldfusion function. I can do this without a
problem if I only need to return one instance of this object.
However, I cannot seem to return an array of this object (I need to
return multiple instances of this object, kind of like a query, but
for programming purposes it needs to stay as an object).
It seems that the webservicing function hates my return type.
If I try to make an array of the object, it does not like array or
the object as the return type. However, when I take this function
out of the cfc, and make it a cfm, it gets the array of objects
just fine. So, I think I am having issues with the return type on
the <cffunction> tag. So I came up with the idea of creating
another object which will hold an array of the first object and
using the second object as the return type. Here is some psuedo
code of the function I am working on:
<cffunction name="SelectGames" access="remote"
returntype="ArrayOfGames" output="false">
<!-- arguments --->
<!--- query --->
<cfobject component = "myArray" name>
<cfobject component="games" name="test">
<cfset counter = 0>
<cfloop query="getevents">
<cfset counter = counter + 1>
<cfset test.Game_id = event_id>
<cfset test.gameDate = eventdate>
<cfset test.Starttime = starttime>
<cfset test.Place = place>
<cfset test.Level = level>
<cfset test.Sport = sport>
<cfset test.Gender = division>
<cfset test.Opponent = opponent_id>
<cfset test.Type = type>
<cfset test.Link = spec_name>
<cfset myArray.gamesArray[counter] = test>
</cfloop>
<cfreturn myArray>
</cffunction>
It keeps telling me that it does not recognize the return
type.
Here are examples of the two objects I am using from the 2
dif. cfc files:
<cfcomponent>
<cfproperty name="gamesArray" type="array">
</cfcomponent>
<cfcomponent>
<cfproperty name="Game_id" type="numeric">
<cfproperty name="gameDate" type="date">
<cfproperty name="Starttime" type="string">
<cfproperty name="Place" type="string">
<cfproperty name="Level" type="string">
<cfproperty name="Sport" type="string">
<cfproperty name="Gender" type="string">
<cfproperty name="Opponent" type="string">
<cfproperty name="Type" type="string">
<cfproperty name="Link" type="string">
</cfcomponent>
Feel free to post any questions to clear anything up, I know
this is confusing and I probably did a poor job of explaining my
problem. Also, if I throw this code into a cfm and try to make an
array of games, it works, this is the code I got it to work with:
<cfset myArray = newArray(1)>
<cfloop query="getevents">
<cfset counter = counter + 1>
<cfset test.Game_id = event_id>
<cfset test.gameDate = eventdate>
<cfset test.Starttime = starttime>
<cfset test.Place = place>
<cfset test.Level = level>
<cfset test.Sport = sport>
<cfset test.Gender = division>
<cfset test.Opponent = opponent_id>
<cfset test.Type = type>
<cfset test.Link = spec_name>
<cfset myArray[counter] = test>
</cfloop>
I guess my problem is I do not know how to specify a type for
an array.The return type of this FUNCTION would be returnType="array".
No matter
what kind of data the array contained.
That's what I get for fast proofing.
Ian Skinner wrote:
> I would have to play with your code more if this does
not clear it up
> for you, but lets start with this simple concept first.
>
> You mentioned "typing the array" several times.
ColdFusion is typeless,
> you don't type an array, it is just array. An array of
strings is the
> same as an array of integers which is the same as an
array of objects.
>
> So if you had a function something like this.
>
> <cffunction returnType="array" ...>
> <cfset theArray = arrayNew()>
>
> <cfloop ...>
> <cfset arrayAppend(theArray, newObject)>
> </cfloop>
>
> <cfreturn theArray>
> </cffunction>
>
> The return type of this function would be
returnType="array". No matter what
> kind of data the array contained.
>
> mwiley63 wrote:
>> I just picked up coldfusion about a month ago, so my
coldfusion lingo
>> sucks. I have been programming in C++ for over 5
years now and will
>> be using a lot of C++ terminology to help avoid any
confusion. I am
>> writing a cfc function that preforms web servicing.
This function
>> needs to return an object/class that is defined in
another coldfusion
>> function. I can do this without a problem if I only
need to return
>> one instance of this object. However, I cannot seem
to return an
>> array of this object (I need to return multiple
instances of this
>> object, kind of like a query, but for programming
purposes it needs to
>> stay as an object).
>> It seems that the webservicing function hates my
return type. If I
>> try to make an array of the object, it does not like
array or the
>> object as the return type. However, when I take this
function out of
>> the cfc, and make it a cfm, it gets the array of
objects just fine.
>> So, I think I am having issues with the return type
on the
>> <cffunction> tag. So I came up with the idea
of creating another
>> object which will hold an array of the first object
and using the
>> second object as the return type. Here is some
psuedo code of the
>> function I am working on:
>>
>> <cffunction name="SelectGames" access="remote"
>> returntype="ArrayOfGames" output="false">
>> <!-- arguments --->
>> <!--- query --->
>> <cfobject component = "myArray" name>
>> <cfobject component="games" name="test">
>> <cfset counter = 0>
>> <cfloop query="getevents">
>> <cfset counter = counter + 1>
>> <cfset test.Game_id = event_id>
>> <cfset test.gameDate = eventdate>
>> <cfset test.Starttime = starttime>
>> <cfset test.Place = place>
>> <cfset test.Level = level>
>> <cfset test.Sport = sport>
>> <cfset test.Gender = division>
>> <cfset test.Opponent = opponent_id>
>> <cfset test.Type = type>
>> <cfset test.Link = spec_name>
>> <cfset myArray.gamesArray[counter] = test>
>> </cfloop>
>> <cfreturn myArray>
>> </cffunction>
>>
>> It keeps telling me that it does not recognize the
return type.
>> Here are examples of the two objects I am using from
the 2 dif. cfc
>> files:
>> <cfcomponent>
>> <cfproperty name="gamesArray" type="array">
>> </cfcomponent>
>> <cfcomponent>
>> <cfproperty name="Game_id" type="numeric">
>> <cfproperty name="gameDate" type="date">
>> <cfproperty name="Starttime" type="string">
>> <cfproperty name="Place" type="string">
>> <cfproperty name="Level" type="string">
>> <cfproperty name="Sport" type="string">
>> <cfproperty name="Gender" type="string">
>> <cfproperty name="Opponent" type="string">
>> <cfproperty name="Type" type="string">
>> <cfproperty name="Link" type="string">
>> </cfcomponent>
>>
>> Feel free to post any questions to clear anything
up, I know this is
>> confusing and I probably did a poor job of
explaining my problem.
>> Also, if I throw this code into a cfm and try to
make an array of
>> games, it works, this is the code I got it to work
with:
>> <cfset myArray = newArray(1)>
>> <cfloop query="getevents">
>> <cfset counter = counter + 1>
>> <cfset test.Game_id = event_id>
>> <cfset test.gameDate = eventdate>
>> <cfset test.Starttime = starttime>
>> <cfset test.Place = place>
>> <cfset test.Level = level>
>> <cfset test.Sport = sport>
>> <cfset test.Gender = division>
>> <cfset test.Opponent = opponent_id>
>> <cfset test.Type = type>
>> <cfset test.Link = spec_name>
>> <cfset myArray[counter] = test>
>> </cfloop>
>>
>> I guess my problem is I do not know how to specify a
type for an array.
>> -
How to call a method using a array of that object?
hey, another array question
for example i have 2 classes one name class and a driver
inside the name class i have method that gets the name
public Name getName1( ) {return name1;}
my question is if i created an array of Name objects in my driver with the following line
Name [ ] n1 = new Name [ ] ;
and i wanna call methods inside the name class using my array of Name that i created how do i do it?
thanks in advancethanks for the reply Maxx
another question regarding arrays
for example if im doing an array of objects Name[ ] n1 = new Name [ ]
and i have a method that removes the name if its the same as the user input
if (n1[ i ].getName.equals(myName))
/ / if they equal it removes it,
else,
/ / the n[ 1 ] stays the same
ive search the forum for previous questions on this but their examples doesnt seems to work, can anyone help? also if end up using this remove method that checks the elements in n1 if it matches it will remove it what should i do to avoid nullpointerexceptions if i wanna shift it all down?
thanks in advance -
Passing Array of java objects to and from oracle database-Complete Example
Hi all ,
I am posting a working example of Passing Array of java objects to and from oracle database . I have struggled a lot to get it working and since finally its working , postinmg it here so that it coudl be helpful to the rest of the folks.
First thinsg first
i) Create a Java Value Object which you want to pass .
create or replace and compile java source named Person as
import java.sql.*;
import java.io.*;
public class Person implements SQLData
private String sql_type = "PERSON_T";
public int person_id;
public String person_name;
public Person () {}
public String getSQLTypeName() throws SQLException { return sql_type; }
public void readSQL(SQLInput stream, String typeName) throws SQLException
sql_type = typeName;
person_id = stream.readInt();
person_name = stream.readString();
public void writeSQL(SQLOutput stream) throws SQLException
stream.writeInt (person_id);
stream.writeString (person_name);
ii) Once you created a Java class compile this class in sql plus. Just Copy paste and run it in SQL .
you should see a message called "Java created."
iii) Now create your object Types
CREATE TYPE person_t AS OBJECT
EXTERNAL NAME 'Person' LANGUAGE JAVA
USING SQLData (
person_id NUMBER(9) EXTERNAL NAME 'person_id',
person_name VARCHAR2(30) EXTERNAL NAME 'person_name'
iv) Now create a table of Objects
CREATE TYPE person_tab IS TABLE OF person_t;
v) Now create your procedure . Ensure that you create dummy table called "person_test" for loggiing values.
create or replace
procedure give_me_an_array( p_array in person_tab,p_arrayout out person_tab)
as
l_person_id Number;
l_person_name Varchar2(200);
l_person person_t;
l_p_arrayout person_tab;
errm Varchar2(2000);
begin
l_p_arrayout := person_tab();
for i in 1 .. p_array.count
loop
l_p_arrayout.extend;
insert into person_test values(p_array(i).person_id, 'in Record '||p_array(i).person_name);
l_person_id := p_array(i).person_id;
l_person_name := p_array(i).person_name;
l_person := person_t(null,null);
l_person.person_id := l_person_id + 5;
l_person.person_name := 'Out Record ' ||l_person_name ;
l_p_arrayout(i) := l_person;
end loop;
p_arrayout := l_p_arrayout;
l_person_id := p_arrayout.count;
for i in 1 .. p_arrayout.count
loop
insert into person_test values(l_person_id, p_arrayout(i).person_name);
end loop;
commit;
EXCEPTION WHEN OTHERS THEN
errm := SQLERRM;
insert into person_test values(-1, errm);
commit;
end;
vi) Now finally create your java class which will invoke the pl/sql procedure and get the updated value array and then display it on your screen>Alternatively you can also check the "person_test" tbale
import java.util.Date;
import java.io.*;
import java.sql.*;
import oracle.sql.*;
import oracle.jdbc.driver.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class ArrayDemo
public static void passArray() throws SQLException
Connection conn = getConnection();
ArrayDemo a = new ArrayDemo();
Person pn1 = new Person();
pn1.person_id = 1;
pn1.person_name = "SunilKumar";
Person pn2 = new Person();
pn2.person_id = 2;
pn2.person_name = "Superb";
Person pn3 = new Person();
pn3.person_id = 31;
pn3.person_name = "Outstanding";
Person[] P_arr = {pn1, pn2, pn3};
Person[] P_arr_out = new Person[3];
ArrayDescriptor descriptor =
ArrayDescriptor.createDescriptor( "PERSON_TAB", conn );
ARRAY array_to_pass =
new ARRAY( descriptor, conn, P_arr);
OracleCallableStatement ps =
(OracleCallableStatement )conn.prepareCall
( "begin give_me_an_array(?,?); end;" );
ps.setARRAY( 1, array_to_pass );
ps.registerOutParameter( 2, OracleTypes.ARRAY,"PERSON_TAB" );
ps.execute();
oracle.sql.ARRAY returnArray = (oracle.sql.ARRAY)ps.getArray(2);
Object[] personDetails = (Object[]) returnArray.getArray();
Person person_record = new Person();
for (int i = 0; i < personDetails.length; i++) {
person_record = (Person)personDetails;
System.out.println( "row " + i + " = '" + person_record.person_name +"'" );
public static void main (String args[]){
try
ArrayDemo tfc = new ArrayDemo();
tfc.passArray();
catch(Exception e) {
e.printStackTrace();
public static Connection getConnection() {
try
Class.forName ("oracle.jdbc.OracleDriver");
return DriverManager.getConnection("jdbc:oracle:thin:@<<HostNanem>>:1523:VIS",
"username", "password");
catch(Exception SQLe) {
System.out.println("IN EXCEPTION BLOCK ");
return null;
and thats it. you are done.
Hope it atleast helps people to get started. Comments are appreciated. I can be reached at ([email protected]) or [email protected]
Thanks
Sunil.sHi Sunil,
I've a similar situation where I'm trying to insert Java objects in db using bulk insert. My issue is with performance for which I've created a new thread.
http://forum.java.sun.com/thread.jspa?threadID=5270260&tstart=30
I ran into your code and looked into it. You've used the Person object array and directly passing it to the oracle.sql.ARRAY constructor. Just curios if this works, cos my understanding is that you need to create a oracle.sql.STRUCT out of ur java object collection and pass it to the ARRAY constructor. I tried ur way but got this runtime exception.
java.sql.SQLException: Fail to convert to internal representation: JavaBulkInsertNew$Option@10bbf9e
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
at oracle.jdbc.oracore.OracleTypeADT.toDatum(OracleTypeADT.java:239)
at oracle.jdbc.oracore.OracleTypeADT.toDatumArray(OracleTypeADT.java:274)
at oracle.jdbc.oracore.OracleTypeUPT.toDatumArray(OracleTypeUPT.java:115)
at oracle.sql.ArrayDescriptor.toOracleArray(ArrayDescriptor.java:1314)
at oracle.sql.ARRAY.<init>(ARRAY.java:152)
at JavaBulkInsertNew.main(JavaBulkInsertNew.java:76)
Here's a code snippet I used :
Object optionVal[] = {optionArr[0]}; // optionArr[0] is an Option object which has three properties
oracle.sql.ArrayDescriptor empArrayDescriptor = oracle.sql.ArrayDescriptor.createDescriptor("TT_EMP_TEST",conn);
ARRAY empArray = new ARRAY(empArrayDescriptor,conn,optionVal);If you visit my thread, u'll see that I'm using STRUCT and then pass it to the ARRAY constructor, which works well, except for the performance issue.
I'll appreciate if you can provide some information.
Regards,
Shamik -
Best way to perform the same task wih arrays of different Objects
Hello all.
This isn't an XPath question, it's a much lower-level Java Object question, but it involves XPath. I hope that doesn't distract from the question, or confuse anything.
I have 4-5 different types of Objects (call them A, B, C, etc.) that each contain an array of other Objects (call them a[], b[], c[], etc.)
a, b, c, etc., each have an Xpath object and and XPathExpression. When I create each XPath object I assign it a NamespaceContext object which contains the namespaces needed for that XPath.
When I create, for example, an A object, I pass is constructor an array of a and an array of Namespaces. With each a object I need to:
1. create a NamespaceContext object
2. go through all the Namespace objects and if its route matches,
(if Namespace.route == a.getRoute() )
3. add that Namespace to the NamespaceContext Object,
4. assign the NamespaceContext to the XPath object, and finally
5. create the a object, passing it the XPath object
My problem / question is: I also have to do the same thing with B and b[], C and c[], etc. It's not that long of a process, not that much code, but all the same, I was wondering what the best way to write this code once would be, and have it work for all the different types of Objects.
In other words, I'd like to write a mehod, call it assignNamespaces(), that accepts an array of Objects(a[], b[], c[], etc.) and an array of Namespaces, creates the XPath Object for each a, b, c, etc., and that creates and returns an array of a[],b[],c[], etc., sending the XPath Object as a parameter.
That way when I create for example an A Object, I call:
class A
ObjectsWithXpath[] objectsWithXPath;
this..objectsWithXPath = assignNamespaces(objectsWithXPath,namespaces);
Should the assgnNamespaces() method simply use Class.forName() to see what type of Object it is and do a cast accordingly, or is there some other, more elegant way of doing this?
I hope I've explained myself, and haven't bored you ...
Thanks in advance,
BobThanks for your reply!
I poked around a bit looking into Factory classes. I've used them a million times but never actually made one. At any rate, they seem like a good idea when you have a bunch of different classes that are similar but not equal.
In my case my classes ONLY have the XPathExpression in common. Which means that I'd have to make a base abstract class with a bunch of methods of which only a percentage are defined by any class that extends it. In other words, if I had 3 classes -- a, b and c -- that extend the base abstract class, and each had 5 getters and setters, the base abstract class would have 15 methods, 5 only used by a, 5 only used by b and 5 only used by c.
It seemed a bit ugly to me. Besides, I only have 3 classes. I decided to factor out the inner loop, which is about 70% of the code, stick it in a utility class, and call it from there. I am repeating some code still, but it isn't that bad, and it saves me having to define an interface, an abstract class, a Factory class, etc.
It ain't perfect, but then nothing ever is.
Thanks for all the help! Viva the Java community!
Bob -
It is interesting why java.lang.reflect.Array.newInstance() returns
Object, but not more specific Object[]?Array.newInstance(int.class, length)
-
Method signature of a two dimensional array of an object
Hi,
Does anyone know how to set the method signature of a two dimensional array of an object (e.g. : String[][]).
Thank you.using javap for the following function:
public int testFunction(String myStr[][]);
public int disconnectServer(java.lang.String[][]);
/* ([[Ljava/lang/String;)I */
so the signature is:
([[Ljava/lang/String;)I -
Newbie - help needed with array and dictionary objects
Hi all
Please see the code below. I've posted this code in another thread however the original issue was resolved and this is now a new issue I'm having although centered around the same code.
The issue is that I'm populating an array with dictionary objects. each dictionary object has a key and it's value is another array of custom objects.
I've found that the code runs without error and I end up with my array as I'm expecting however all of the dictionary objects are the same.
I assume it's something to do with pointers and/or re-using the same objects but i'm new to obj-c and pointers so i am a bit lost.
Any help again is very much appreciated.
// Open the database connection and retrieve minimal information for all objects.
- (void)initializeDatabase {
NSMutableArray *authorArray = [[NSMutableArray alloc] init];
self.authors = authorArray;
[authorArray release];
// The database is stored in the application bundle.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"books.sql"];
// Open the database. The database was prepared outside the application.
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
// Get the primary key for all books.
const char *sql = "SELECT id, author FROM author";
sqlite3_stmt *statement;
// Preparing a statement compiles the SQL query into a byte-code program in the SQLite library.
// The third parameter is either the length of the SQL string or -1 to read up to the first null terminator.
if (sqlite3preparev2(database, sql, -1, &statement, NULL) == SQLITE_OK) {
// We "step" through the results - once for each row.
// We start with Letter A...we're building an A - Z grouping
NSString *letter = @"A";
NSMutableArray *tempauthors = [[NSMutableArray alloc] init];
while (sqlite3_step(statement) == SQLITE_ROW) {
author *author = [[author alloc] init];
author.primaryKey = sqlite3columnint(statement, 0);
author.title = [NSString stringWithUTF8String:(char *)sqlite3columntext(statement, 0)];
// FOLLOWING WAS LEFT OVER FROM ORIGINAL COMMENTS IN SQLBooks example....
// We avoid the alloc-init-autorelease pattern here because we are in a tight loop and
// autorelease is slightly more expensive than release. This design choice has nothing to do with
// actual memory management - at the end of this block of code, all the book objects allocated
// here will be in memory regardless of whether we use autorelease or release, because they are
// retained by the books array.
// if the author starts with the Letter we currently have, add it to the temp array
if ([[author.title substringToIndex:1] compare:letter] == NSOrderedSame){
[tempauthors addObject:author];
} // if this is different letter, then we need to deal with that too...
else {
// create a dictionary to store the current tempauthors array in...
NSDictionary *tempDictionary = [NSDictionary dictionaryWithObject:tempauthors forKey:@"authors"];
// add the dictionary to our appDelegate-level array
[authors addObject:tempDictionary];
// now prepare for the next loop...
// set the new letter...
letter = [author.title substringToIndex:1];
// remove all of the previous authors so we don't duplicate...
[tempauthors removeAllObjects];
// add the current author as this was the one that didn't match the Letter and so
// never went into the previous array...
[tempauthors addObject:author];
// release ready for the next loop...
[author release];
// clear up the remaining authors that weren't picked up and saved in the "else" statement above...
if (tempauthors.count > 0){
NSDictionary *tempDictionary = [NSDictionary dictionaryWithObject:tempauthors forKey:@"authors"];
[authors addObject:tempDictionary];
else {
printf("Failed preparing statement %s
", sqlite3_errmsg(database));
// "Finalize" the statement - releases the resources associated with the statement.
sqlite3_finalize(statement);
} else {
// Even though the open failed, call close to properly clean up resources.
sqlite3_close(database);
NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database));
// Additional error handling, as appropriate...
Message was edited by: dotnetterOk, so I know what the issue is now...I just don't know enough to be able to resolve it!
it's the tempAuthors objects.
It's an NSMutableArray which is create on the line before the start of the WHILE loop.
Having looked through the debugger, I can see that each dictionary object is created (with different codes which I assume are memory addresses) so all is well there. However, on each iteration of the loop in the middle there is an IF...ELSE... statement which in the ELSE section is clearing all objects from the tempAuthors array and beginning to repopulate it again.
Looking at the containing dictionary objects in the debugger I can see that the tempAuthors object that each contains has the same code (again, I'm assuming this is a memory address) - so if I understand correctly, it's the same object...I assumed that when I created the dictionary using the dictionWithObject call that I would be passing in a copy of the object, but it's referencing back to the object which I then go on to change.
Assuming the above is correct, I've tried several "stabs in the dark" at fixing it.
I've tried relasing the tempAuthors object within the ELSE and initialising it again via an alloc...init - but this didn't work and again looking through the debugger it looks as though it was confused as to which object it was supposed to be using on the following iteration of the WHILE loop (it tried to access the released object).
Having read a little more about memory management can someone tell me if I'm correct in saying that the above is because the tempAuthors object is declare outside the scope of the WHILE loop yet I then try to re-instantiate it within the loop (does that make sense???).
Sorry for the long post...the more I can understand the process the less I can hopefully stop relying on others for help so much.
I am continuing to read up on memory management etc but just not there yet.
Regards
Wayne -
i seen array storing many integers, strings, char. but how to use array to store objects of a class..
how to define those objects created from a defined class in a array. how to obtain each instance variable of the object stored in the array.
maybe can use a student class to illustrate.i got yr idea man!!
so whenever the compiler see
String s = "Hola Mundo";
it is simply equal to String s = new String("Hola
Mundo");
that why we can directly access value to array[0]=
"hi";
array[0]=new Student();
array[0].setName = "Hola Mundo"
is also similar in certain way to
array[0]= new String("Hola Mundo");
i right again this time?Nope waaaay off.
If Name is public in Student then it would be:
array[0].name = "Hola Mundo";
if name is private and you have a public setter setName(String newName) then it would be:
array[0].setName("Hola Mundo");
and if array is an array of strings, then array[0] = "Hola Mundo";
is correct.
PS: you still need to read the tutorials. I am out now. -
Array of CreditCard objects - PLEASE HELP!
My situation is this: I need to create an array of CreditCard objects. The problem is that when I try to invoke the methods getName, getNumber, or getLimit, the compiler recognizes the array (cardholders) as a variable.
My coding is this.
for(int i=0;fileInput.hasNext();i++)
CreditCard[] cardholders = new CreditCard[records];
int cardNum = Integer.parseInt(fileInput.next());
String cardName = fileInput.nextLine();
double cardLimit = Double.parseDouble(fileInput.nextLine());
cardholders[i] = new CreditCard(cardNum, cardName, cardLimit);
But when I try to access a CreditCard object, through cardholders[4] (for example), the error cannot find symbol appears. PLEASE HELP ITS DRIVING ME CRAZY.
THANKSYou are lacking basic Java knowledge, micksabox. The following tutorial is on Arrays in Java. The one after on the Java Collections Framework, you might want to learn about as the better solution for working with sets and lists of objects in Java.
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.html
http://java.sun.com/docs/books/tutorial/collections/index.html
Maybe you are looking for
-
Need help for SQL SELECT query to fetch XML records from Oracle tables having CLOB field
Hello, I have a scenario wherein i need to fetch records from several oracle tables having CLOB fields(which is holding XML) and then merge them logically to form a hierarchy XML. All these tables are related with PK-FK relationship. This XML hierarc
-
My ipod shows a sign like a cross with a circle, what do that mean?
my ipod shows a sign like a cross with a circle, what do that mean?
-
Profit center accounting and cost center relationship
Experts, in the future as we look to tie the PCA cube with the CO cube, the referential integrity will be important. What I see as being important is capturing the profit center, cost center and account that was used at the transactional level and n
-
Replaced Display and see dots.
I took my White MacBook to the genius bar because the batter wouldn't charge. I have the one year limited warranty and it's about to expire (unsure if I should buy the warranty bc it's too expensive for me), and While I was there I brought up another
-
Can I use my iPad2 to change Ipad Air?
Can I use my iPad2 to change Ipad Air?