Array Of Objects In Java: How To Create, Initialize And Use

文章推薦指數: 80 %
投票人數:10人

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{ privateStringname; privateintempId; //constructor publicEmployee(Stringname,intempId){ this.name=name; this.empId=empId; } publicStringgetName(){ returnname; } publicintgetempId(){ returnempId; } //overriddenfunctionssinceweareworkingwitharrayofobjects @Override publicStringtoString(){ return"{"+"name='"+name+'\''+ ",EmpId="+empId+'}'; } //compareTomethodoverriddenforsortingarrayofobjects @Override publicintcompareTo(Employeeo){ if(this.empId!=o.getempId()){ returnthis.empId-o.getempId(); } returnthis.name.compareTo(o.getName()); } } //mainclass classMain{ publicstaticvoidmain(String[]args) { //arrayofEmployeeobjects Employee[]employees={newEmployee("Rick",1),newEmployee("Sam",20), newEmployee("Adi",5),newEmployee("Ben",10)}; //printoriginalarray System.out.println("OriginalArrayofEmployeeobjects:"); System.out.println(Arrays.toString(employees)); //sortarrayonempId Arrays.sort(employees); //displaysortedarray System.out.println("\nSortedArrayofEmployeeobjects:"); System.out.println(Arrays.toString(employees)); } } Output: Notethatintheaboveprogram,theEmployeeclassimplementsComparableinterface.Secondly,themethodcompareToisoverriddentosortthegivenarrayofobjectsontheempIdfield. Also,themethod‘toString’isoverriddeninordertofacilitatetheconversionofthearrayofobjectstoastring. FrequentlyAskedQuestions Q#1)CanyouhaveanArrayofObjectsinJava? Answer:Yes.Javacanhaveanarrayofobjectsjustlikehowitcanhaveanarrayofprimitivetypes. Q#2)WhatisanArrayofObjectsinJava? Answer:InJava,anarrayisadynamicallycreatedobjectthatcanhaveelementsthatareprimitivedatatypesorobjects.Thearraymaybeassignedvariablesthatareoftypeobject. Q#3)HowdoyouSortObjectsinJava? Answer:TosortobjectsinJava,weneedtoimplementthe‘Comparable’interfaceandoverridethe‘compareTo’methodaccordingtoaparticularfield.Thenwecanusethe‘Arrays.sort’methodtosortanarrayofobjects. Q#4)HowdoyouSortObjectsinArrayList? Answer:ArrayListcanbesortedusingtheCollections.sort()methoddirectly.TheCollections.sort()methodsortstheelementsnaturallyinascendingorder. Conclusion Inthistutorial,wediscussedthetopic‘ArrayofObjects’alongwiththevarioussubtopicsrelatedtoanarrayofobjects.Wesawexamplesofinitializing&sortinganarrayofobjects. Forsortingtheclasswhoseobjectsaretobesortedshouldimplementthe‘Comparable’interfaceandalsooverridethe‘compareTo’method.Toprintthecontentsofthe‘Arrayofobjects’,weshouldalsooverridethe‘toString’methodsothatwecanwriteallthecontentsofeachobject. =>VisitHereToSeeTheJavaTrainingSeriesForAll. RecommendedReading JavaArray-Declare,Create&InitializeAnArrayInJava JavaArrayLengthTutorialWithCodeExamples JavaArray-HowToPrintElementsOfAnArrayInJava? JavaGenericArray-HowToSimulateGenericArraysInJava? JavaHelloWorld-CreateYourFirstProgramInJavaToday MultiDimensionalArraysInJava(2dand3dArraysInJava) JavaInterfaceandAbstractClassTutorialWithExamples JAVATutorialForBeginners:100+Hands-onJavaVideoTutorials AboutSoftwareTestingHelpHelpingourcommunitysince2006! MostpopularportalforSoftwareprofessionalswith240million+visitsand300,000+followers!YouwillabsolutelyloveourcreativecontentonSoftwareToolsandServicesReviews! RecommendedReading JavaArray–Declare,Create&InitializeAnArrayInJava JavaArrayLengthTutorialWithCodeExamples JavaArray–HowToPrintElementsOfAnArrayInJava? JavaGenericArray–HowToSimulateGenericArraysInJava? JavaHelloWorld–CreateYourFirstProgramInJavaToday MultiDimensionalArraysInJava(2dand3dArraysInJava) JavaInterfaceandAbstractClassTutorialWithExamples JAVATutorialForBeginners:100+Hands-onJavaVideoTutorials JOINOurTeam!



請為這篇文章評分?