Array Of Objects In Java: How To Create, Initialize And Use
文章推薦指數: 80 %
An array of objects is created using the 'Object' class. The following statement creates an Array of Objects. Class_name [] objArray;.
Skiptocontent
Menu
MENUMENUHomeResourcesFREEeBooksQATesting
FreeQATrainingTestCasesSDLCTestLink
SoftwareTestingBugZillaMobileTestingJIRA
AgileMethodologyDatabaseTestingETLTesting
QualityAssuranceTestManagementSAPERPTesting
Courses
SoftwareTesting(LIVECourse)Selenium(LIVECourse)
SoftwareTestingSeleniumQTP/UFTJIRAVideosRubyCucumber
Automation
AutomationTestingSoapUIJIRAAppiumKarateFramework
SeleniumQTP/UFTALMQCPostman
JMeterLoadRunnerAPITestingRobotFramework
TestNGJUnitEclipseMaven
TypesOfTesting
AllTestingTypesRegressionTestingUnitTestingSmokeTesting
FunctionalTestingIntegrationTestingSystemTestingUsabilityTesting
UATTestingBetaTestingBlackBoxTestingWhiteBoxtesting
LoadTestingStressTestingSecurityTestingPerformanceTesting
Tutorials
C++C#DevOpsVBScriptTeamManagementComputerNetworkingJest
PythonJAVAUNIXSVNAngularJSSpockLaravel
SpecFlowJSONFlaskSOAtestMockitoKarma
MachineLearningBlockchainGitHubGatlingWiremock
Data
OraclePL/SQL
DataWarehouseExcelVBA
BigDataJDBC
MongoDB
Menu
MENUMENUHomeResourcesFREEeBooksQATesting
FreeQATrainingTestCasesSDLCTestLink
SoftwareTestingBugZillaMobileTestingJIRA
AgileMethodologyDatabaseTestingETLTesting
QualityAssuranceTestManagementSAPERPTesting
Courses
SoftwareTesting(LIVECourse)Selenium(LIVECourse)
SoftwareTestingSeleniumQTP/UFTJIRAVideosRubyCucumber
Automation
AutomationTestingSoapUIJIRAAppiumKarateFramework
SeleniumQTP/UFTALMQCPostman
JMeterLoadRunnerAPITestingRobotFramework
TestNGJUnitEclipseMaven
TypesOfTesting
AllTestingTypesRegressionTestingUnitTestingSmokeTesting
FunctionalTestingIntegrationTestingSystemTestingUsabilityTesting
UATTestingBetaTestingBlackBoxTestingWhiteBoxtesting
LoadTestingStressTestingSecurityTestingPerformanceTesting
Tutorials
C++C#DevOpsVBScriptTeamManagementComputerNetworkingJest
PythonJAVAUNIXSVNAngularJSSpockLaravel
SpecFlowJSONFlaskSOAtestMockitoKarma
MachineLearningBlockchainGitHubGatlingWiremock
Data
OraclePL/SQL
DataWarehouseExcelVBA
BigDataJDBC
MongoDB
LastUpdated:August7,2022
InthisJavaTutorial,youcanLearntoCreate,Initialize,SorttheArrayofObjectsinJavawithCompleteCodeExamples:
WhatisanArrayofObjects?
Asweallknow,theJavaprogramminglanguageisallaboutobjectsasitisanobject-orientedprogramminglanguage.
Ifyouwanttostoreasingleobjectinyourprogram,thenyoucandosowiththehelpofavariableoftypeobject.Butwhenyouaredealingwithnumerousobjects,thenitisadvisabletouseanarrayofobjects.
=>CheckOutThePerfectJavaTrainingGuideHere.
Javaiscapableofstoringobjectsaselementsofthearrayalongwithotherprimitiveandcustomdatatypes.Notethatwhenyousay‘arrayofobjects’,itisnottheobjectitselfthatisstoredinthearraybutthereferencesoftheobject.
Inthistutorial,youwillgetacquaintedwiththecreation,initialization,sortingaswellasexamplesofthearrayofobjectsinJava.
WhatYouWillLearn:HowToCreateAnArrayOfObjectsInJava?InitializeArrayOfObjectsExampleProgramForAnArrayOfObjectsInJavaHowToSortAnArrayOfObjectsInJava?FrequentlyAskedQuestionsConclusionRecommendedReading
HowToCreateAnArrayOfObjectsInJava?
Anarrayofobjectsiscreatedusingthe‘Object’class.
ThefollowingstatementcreatesanArrayofObjects.
Class_name[]objArray;
Alternatively,youcanalsodeclareanArrayofObjectsasshownbelow:
Class_nameobjArray[];
BoththeabovedeclarationsimplythatobjArrayisanarrayofobjects.
So,ifyouhaveaclass‘Employee’thenyoucancreateanarrayofEmployeeobjectsasgivenbelow:
Employee[]empObjects;
OR
EmployeeempObjects[];
Thedeclarationsofthearrayofobjectsabovewillneedtobeinstantiatedusing‘new’beforebeingusedintheprogram.
Youcandeclareandinstantiatethearrayofobjectsasshownbelow:
Employee[]empObjects=newEmployee[2];
Notethatonceanarrayofobjectsisinstantiatedlikeabove,theindividualelementsofthearrayofobjectsneedtobecreatedusingnew.
Theabovestatementwillcreateanarrayofobjects‘empObjects’with2elements/objectreferences.
InitializeArrayOfObjects
Oncethearrayofobjectsisinstantiated,youhavetoinitializeitwithvalues.Asthearrayofobjectsisdifferentfromanarrayofprimitivetypes,youcannotinitializethearrayinthewayyoudowithprimitivetypes.
Inthecaseofanarrayofobjects,eachelementofarrayi.e.anobjectneedstobeinitialized.Wealreadydiscussedthatanarrayofobjectscontainsreferencestotheactualclassobjects.Thus,oncethearrayofobjectsisdeclaredandinstantiated,youhavetocreateactualobjectsoftheclass.
Onewaytoinitializethearrayofobjectsisbyusingtheconstructors.Whenyoucreateactualobjects,youcanassigninitialvaluestoeachoftheobjectsbypassingvaluestotheconstructor.Youcanalsohaveaseparatemembermethodinaclassthatwillassigndatatotheobjects.
Thefollowingprogramshowstheinitializationofarrayobjectsusingtheconstructor.
HerewehaveusedtheclassEmployee.Theclasshasaconstructorthattakesintwoparametersi.e.employeenameandemployeeId.Inthemainfunction,afteranarrayofemployeesiscreated,wegoaheadandcreateindividualobjectsoftheclassemployee.
Thenwepassinitialvaluestoeachoftheobjectsusingtheconstructor.
Theoutputoftheprogramshowsthecontentsofeachobjectthatwasinitializedpreviously.
classMain{
publicstaticvoidmain(Stringargs[]){
//createarrayofemployeeobject
Employee[]obj=newEmployee[2];
//create&initializeactualemployeeobjectsusingconstructor
obj[0]=newEmployee(100,"ABC");
obj[1]=newEmployee(200,"XYZ");
//displaytheemployeeobjectdata
System.out.println("EmployeeObject1:");
obj[0].showData();
System.out.println("EmployeeObject2:");
obj[1].showData();
}
}
//EmployeeclasswithempIdandnameasattributes
classEmployee{
intempId;
Stringname;
//Employeeclassconstructor
Employee(inteid,Stringn){
empId=eid;
name=n;
}
publicvoidshowData(){
System.out.print("EmpId="+empId+""+"EmployeeName="+name);
System.out.println();
}
}
Output:
TheexampleprogramthatwehavegivenbelowshowsamemberfunctionoftheEmployeeclassthatisusedtoassigntheinitialvaluestotheEmployeeobjects.
ExampleProgramForAnArrayOfObjectsInJava
GivenisacompleteexamplethatdemonstratesthearrayofobjectsinJava.
Inthisprogram,wehaveanEmployeeclassthathasemployeeId(empId)andemployeename(name)asfieldsand‘setData’&‘showData’asmethodsthatassigndatatoemployeeobjectsanddisplaythecontentsofemployeeobjectsrespectively.
Inthemainmethodoftheprogram,wefirstdefineanarrayofEmployeeobjects.Notethatthisisanarrayofreferencesandnotactualobjects.Thenusingthedefaultconstructor,wecreateactualobjectsfortheEmployeeclass.Next,theobjectsareassigneddatausingthesetDatamethod.
Lastly,objectsinvoketheshowDatamethodtodisplaythecontentsoftheEmployeeclassobjects.
classMain{
publicstaticvoidmain(Stringargs[]){
//createarrayofemployeeobject
Employee[]obj=newEmployee[2];
//createactualemployeeobject
obj[0]=newEmployee();
obj[1]=newEmployee();
//assigndatatoemployeeobjects
obj[0].setData(100,"ABC");
obj[1].setData(200,"XYZ");
//displaytheemployeeobjectdata
System.out.println("EmployeeObject1:");
obj[0].showData();
System.out.println("EmployeeObject2:");
obj[1].showData();
}
}
//EmployeeclasswithempIdandnameasattributes
classEmployee{
intempId;
Stringname;
publicvoidsetData(intc,Stringd){
empId=c;
name=d;
}
publicvoidshowData(){
System.out.print("EmpId="+empId+""+"EmployeeName="+name);
System.out.println();
}
}
Output:
HowToSortAnArrayOfObjectsInJava?
Likeanarrayofprimitivetypes,anarrayofobjectscanalsobesortedusingthe‘sort’methodoftheArraysclass.
Butthedifferenceisthattheclasstowhichtheobjectsbelongshouldimplementthe‘Comparable’interfacesothatthearrayofobjectsaresorted.Youalsoneedtooverridethe‘compareTo’methodthatwilldecidethefieldonwhichthearrayistobesorted.Thearrayofobjectsissortedinascendingorderbydefault.
Thefollowingprogramshowsthesortingofanarrayofobjects.WehaveusedanEmployeeclassforthispurposeandthearrayissortedbasedonemployeeId(empId).
importjava.util.*;
//employeeclassimplementingcomparableinterfaceforarrayofobjects
classEmployeeimplementsComparable
延伸文章資訊
- 1Arrays (Java Platform SE 7 ) - Oracle Help Center
This class contains various methods for manipulating arrays (such as sorting and searching). This...
- 2Java Array Class Tutorial - java.util.Arrays Class with Examples
The Arrays class was introduced in Java 1.2 and the methods it contains are mostly used for manip...
- 3Java 物件陣列的運用 - 翻轉工作室
//Ex5_3.java. /* 請建立一套薪資管理系統,允許輸入員工資料,並印出薪資表 */. import java.util.*;. class Employee { // 員工資料類別....
- 4Java Array - Javatpoint
- 5How to Create Array of Objects in Java - Guru99