Java Array Class Tutorial - java.util.Arrays Class with Examples

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

The Arrays class was introduced in Java 1.2 and the methods it contains are mostly used for manipulation of the array including searching, ... 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 ThisTutorialCoverstheArrayClassinJavaandthemethodsofjava.util.arraysClassalongwithDetailedDescription&ExamplesofArrayClassmethods: The‘Arrays’classisamemberofthe‘java.util’package.ThisisapartoftheJavaCollectionsframeworkandprovidesmethodstocreate,accessandmanipulateJavaarraysdynamically. AllthemethodsprovidedbytheArraysclassarestaticinnatureandaremethodsofthe‘Object’class.Asthemethodsarestatic,theycanbeaccessedusingtheclassnameitself. =>CheckALLJavaTutorialsHere. WhatYouWillLearn:JavaArrayClassJavaArraysMethods#1)asList#2)binarySearch#3)copyOf#4)copyOfRange#5)Equals#6)Fill#7)Sort#8)toString#9)hashCodeFrequentlyAskedQuestionsConclusionRecommendedReading JavaArrayClass TheArraysclasswasintroducedinJava1.2andthemethodsitcontainsaremostlyusedformanipulationofthearrayincludingsearching,sorting,etc.Thearraysclassprovidesoverloadedmethodsforalmostallthedatatypes. TheclasshierarchyforArraysclassisshownbelow: TheArraysclassextendsfromObjectclassanditsmethodsaremethodsofObjectclass. ThegeneralsyntaxtoaccessanymethodofArraysclassis: Arrays.<method_name>; Intheupcomingsection,wewilllistoutthevariousmethodsprovidedbytheArraysclass. JavaArraysMethods ThefollowingtablesgiveanintroductiontothevariousmethodsprovidedbytheArraysclass.Herewehavelistedthemainmethods.Notethatmostofthemethodsareoverloadedtoprovidesupportforalltheprimitivetypes. Wewilllisttheprototypeanddescriptionofeachofthefunctions.Theninthefollowingsection,wewilldescribesomeoftheimportantmethodsbyprovidingprogrammingexamples. MethodNamePrototypeDescription asListstaticList< T>asList(Object[] a)Returnsalist(fixed-size)fromspecifiedarray binarySearch Thismethodusesthebinarysearchalgorithm. ShowninthenextcolumnarevariousoverloadsofthebinarySearchmethod.staticintbinarySearch(byte[]a,bytekey)Searchesforakeyinabytearray staticintbinarySearch(byte[]a,intfromIndex,inttoIndex,bytekey)Searchesthekeyacrossthespecifiedrangeinabytearray staticintbinarySearch(char[]a,charkey)Searchesakeyinacharacterarray staticintbinarySearch(char[]a,intfromIndex,inttoIndex,charkey)Searchesthekeyacrossthespecifiedrangeinacharacterarray staticintbinarySearch(double[]a,doublekey)Searchesakeyinadoublearray staticintbinarySearch(double[]a,intfromIndex,inttoIndex,doublekey)Searchesthekeyacrossthespecifiedrangeinadoublearray staticintbinarySearch(float[]a,floatkey)Searchesakeyinanarrayoffloats staticintbinarySearch(float[]a,intfromIndex,inttoIndex,floatkey)Searchesthekeyacrossthespecifiedrangeinafloatsarray staticintbinarySearch(int[]a,intkey)Searchesakeyinanintarray staticintbinarySearch(int[]a,intfromIndex,inttoIndex,intkey)Searchesthekeyacrossthespecifiedrangeinanintarray staticintbinarySearch(long[]a,longkey)Searchesakeyinlongarray staticintbinarySearch(long[]a,intfromIndex,inttoIndex,longkey)Searchesthekeyacrossthespecifiedrangeinlongarray staticintbinarySearch(Object[]a,Objectkey)Searchesakeyinanobjectarray staticintbinarySearch(Object[]a,intfromIndex,inttoIndex,Objectkey)Searchesthekeyacrossthespecifiedrangeintheobjectarray staticintbinarySearch(short[]a,shortkey)Searchesakeyinanarrayofshorts staticintbinarySearch(short[]a,intfromIndex,inttoIndex,shortkey)Searchesthekeyacrossthespecifiedrangeinanarrayofshorts staticintbinarySearch(T[]a,Tkey,Comparatorc)Searchesakeyinanarrayofspecifiedobjects staticintbinarySearch(T[]a,intfromIndex,inttoIndex,Tkey,Comparatorc)Searchesthekeyacrossthespecifiedrangeinarrayofobjects MethodNamePrototypeDescription copyOf Themethodisusedtocopythearraywiththespecifiedlength. Nextcolumnliststheoverloadsofthismethodstaticboolean[]copyOf(boolean[]original,intnewLength)Copiesthespecifiedarray.Truncatesorappendsvalues‘false’ifnecessary staticbyte[]copyOf(byte[]original,intnewLength)Copiesthespecifiedarray.Truncatesorappendszerosifnecessary staticchar[]copyOf(char[]original,intnewLength)Copiesthespecifiedarray.Truncatesorappendsnullifnecessary staticdouble[]copyOf(double[]original,intnewLength)Copiesthespecifiedarray.Truncatesorappendszerosifnecessary staticfloat[]copyOf(float[]original,intnewLength)Copiesthespecifiedarray.Truncatesorappendszerosifnecessary staticint[]copyOf(int[]original,intnewLength)Copiesthespecifiedarray.Truncatesorappendszerosifnecessary staticlong[]copyOf(long[]original,intnewLength)Copiesthespecifiedarray.Truncatesorappendszerosifnecessary staticshort[]copyOf(short[]original,intnewLength)Copiesthespecifiedarray.Truncatesorappendszerosifnecessary staticT[]copyOf(T[]original,intnewLength)Copiesthespecifiedarray.Truncatesorappendsnullsifnecessary staticT[]copyOf(U[]original,intnewLength,ClassnewType)Copiesthespecifiedarray.Truncatesorappendsnullsifnecessary copyOfRange Thismethodisusedtocopyaspecifiedrangeinthearray. Theoverloadsforthismethodaregiveninthenextcolumnstaticboolean[]copyOfRange(boolean[]original,intfrom,intto)Copiesthearraywithspecifiedrangeintoanewarray staticbyte[]copyOfRange(byte[]original,intfrom,intto)Copiesthearraywithspecifiedrangeintoanewarray staticchar[]copyOfRange(char[]original,intfrom,intto)Copiesthearraywithspecifiedrangeintoanewarray staticdouble[]copyOfRange(double[]original,intfrom,intto)Copiesthearraywithspecifiedrangeintoanewarray staticfloat[]copyOfRange(float[]original,intfrom,intto)Copiesthearraywithspecifiedrangeintoanewarray staticint[]copyOfRange(int[]original,intfrom,intto)Copiesthearraywithspecifiedrangeintoanewarray staticlong[]copyOfRange(long[]original,intfrom,intto)Copiesthearraywithspecifiedrangeintoanewarray staticshort[]copyOfRange(short[]original,intfrom,intto)Copiesthearraywithspecifiedrangeintoanewarray staticT[]copyOfRange(T[]original,intfrom,intto)Copiesthearraywithspecifiedrangeintoanewarray staticT[]copyOfRange(U[]original,intfrom,intto,ClassnewType)Copiesthearraywithspecifiedrangeintoanewarray MethodNamePrototypeDescription deepEqualsstaticbooleandeepEquals(Object[]a1,Object[]a2)Checksiftwospecifiedarraysaredeeplyequal deepHashCodestaticintdeepHashCode(Object[]a)Returnsahashcodeofthespecifiedarray deepToStringstaticStringdeepToString(Object[]a)Returnsthe"deepcontents"ofthespecifiedarrayinastring Equals Checksiftwospecifiedarraysareequalstaticbooleanequals(boolean[]a,boolean[]a2)Returnstrueifthetwospecifiedbooleanarraysareequal. staticbooleanequals(byte[]a,byte[]a2)Returnstrueifthetwospecifiedbytearraysareequal staticbooleanequals(char[]a,char[]a2)Returnstrueifthetwospecifiedcharacterarraysareequal. staticbooleanequals(double[]a,double[]a2)Returnstrueifthetwospecifieddoublearraysareequal. staticbooleanequals(float[]a,float[]a2)Returnstrueifthetwospecifiedfloatarraysareequal. staticbooleanequals(int[]a,int[]a2)Returnstrueifthetwospecifiedintarraysareequal. staticbooleanequals(long[]a,long[]a2)Returnstrueifthetwospecifiedlongarraysareequal. staticbooleanequals(Object[]a,Object[]a2)ReturnstrueifthetwospecifiedObjectarraysareequal. staticbooleanequals(short[]a,short[]a2)Returnstrueifthetwospecifiedshortarraysareequal. MethodNamePrototypeDescription fill Fillsthearray(allelements)withthespecifiedvalue. Nextcolumngivestheoverloadsforthisfunctionstaticvoidfill(boolean[]a,booleanval)Fillsthebooleanarraywithaspecifiedbooleanvalue staticvoidfill(boolean[]a,intfromIndex,inttoIndex,booleanval)Assignsabooleanvaluetothespecifiedrangeinthebooleanarray. staticvoidfill(byte[]a,byteval)Fillsthebytearraywithaspecifiedbytevalue staticvoidfill(byte[]a,intfromIndex,inttoIndex,byteval)Fillsthebytearraywithspecifiedbytevalueinthegivenrange staticvoidfill(char[]a,charval)Fillsthechararraywithspecifiedcharvalue staticvoidfill(char[]a,intfromIndex,inttoIndex,charval)Fillsthechararrayrangewithspecifiedcharvalue staticvoidfill(double[]a,doubleval)Fillsthedoublearraywithspecifieddoublevalue staticvoidfill(double[]a,intfromIndex,inttoIndex,doubleval)Assignsadoublevaluetothespecifiedrangeinthedoublearray. staticvoidfill(float[]a,floatval)Assignsfloatvaluetothespecifiedrangeinthefloatarray. staticvoidfill(float[]a,intfromIndex,inttoIndex,floatval)Assignsfloatvaluetothespecifiedrangeinthefloatarray. staticvoidfill(int[]a,intval)Assignsintvaluetotheintarray. staticvoidfill(int[]a,intfromIndex,inttoIndex,intval)Assignsintvaluetothespecifiedrangeintheintarray. staticvoidfill(long[]a,intfromIndex,inttoIndex,longval)Assignsalongvaluetothespecifiedrangeinthelongarray. staticvoidfill(long[]a,longval)Assignsalongvaluetothelongarray. staticvoidfill(Object[]a,intfromIndex,inttoIndex,Objectval)AssignsObjectreferencetospecifiedrangeintheObjectarray. staticvoidfill(Object[]a,Objectval)AssignsObjectreferencetothespecifiedobjectarray staticvoidfill(short[]a,intfromIndex,inttoIndex,shortval)Assignsashortvaluetothespecifiedrangeintheshortarray. staticvoidfill(short[]a,shortval)Assignsashortvaluetothespecifiedshortarray. MethodNamePrototypeDescription Sort Sortsthearraypassedasaparametertothemethod. Overloadsaregiveninthenextcolumn. staticvoidsort(byte[]a)Sortsthebytearraynumerically staticvoidsort(byte[]a,intfromIndex,inttoIndex)Sortstherangeofelementsfromthearray staticvoidsort(char[]a)Sortsthecharacterarrayintoascendingnumericalorder. staticvoidsort(char[]a,intfromIndex,inttoIndex)Sortstherangeofelementsinthearrayintoascendingorder. staticvoidsort(double[]a)Sortsthedoublearrayintoascendingnumericalorder. staticvoidsort(double[]a,intfromIndex,inttoIndex)Sortstherangeofelementsfromthearrayintoascendingorder. staticvoidsort(float[]a)Sortsthefloatarrayintoascendingnumericalorder. staticvoidsort(float[]a,intfromIndex,inttoIndex)Sortstherangeofelementsfromthearrayintoascendingorder. staticvoidsort(int[]a)Sortstheintarrayintoascendingnumericalorder. staticvoidsort(int[]a,intfromIndex,inttoIndex)Sortstherangeofelementsfromthearrayintoascendingorder. staticvoidsort(long[]a)Sortsthelongarrayintoascendingnumericalorder. staticvoidsort(long[]a,intfromIndex,inttoIndex)Sortstherangeofelementsfromthearrayintoascendingorder staticvoidsort(Object[]a)Sortsthearrayofobjectsintoascendingorder.Sortingisdoneaccordingtothenaturalorderingofitselements staticvoidsort(Object[]a,intfromIndex,inttoIndex)Sortsthespecifiedrangefromanarrayofobjectsintoascendingorder.Sortingisdoneaccordingtothenaturalorderingofitselements. staticvoidsort(short[]a)Sortsthearrayoftypeshortintoascendingnumericalorder. staticvoidsort(short[]a,intfromIndex,inttoIndex)Sortstherangeofelementsfromthearrayintoascendingorder. staticvoidsort(T[]a,Comparatorc)Sortsthespecifiedarrayofobjects.Theorderofsortingisinducedasperthespecifiedcomparator. staticvoidsort(T[]a,intfromIndex,inttoIndex,Comparatorc)Sortstherangeofelementsfromanarrayofobjectsintheorderspecifiedbythecomparator. MethodNamePrototypeDescription toString Thismethodreturnsthestringrepresentationofagivenarray. DifferentoverloadsofthismethodaregiveninthenextcolumnstaticStringtoString(boolean[]a)Returnsastringrepresentationofabooleanarray staticStringtoString(byte[]a)Returnsastringrepresentationofabytearray staticStringtoString(char[]a)Returnsastringrepresentationofacharacterarray staticStringtoString(double[]a)Returnsastringrepresentationofadoublearray staticStringtoString(float[]a)Returnsastringrepresentationofafloatarray staticStringtoString(int[]a)Returnsastringrepresentationofanintarray staticStringtoString(long[]a)Returnsastringrepresentationofalongarray staticStringtoString(Object[]a)Returnsastringrepresentationofanobjectarray staticStringtoString(short[]a)Returnsastringrepresentationofashortarray MethodNamePrototypeDescription hashCode ThismethodreturnsthehashCodeofthecontentsofthespecifiedarray Theoverloadedmethodsaregiveninthenextcolumn. staticinthashCode(boolean[]a)Returnshashcodeofthecontentsofthebooleanarray staticinthashCode(byte[]a)Returnshashcodeofthecontentsofthebytearray staticinthashCode(char[]a)Returnshashcodeofthecontentsofthecharacterarray staticinthashCode(double[]a)Returnshashcodeofthecontentsofadoublearray staticinthashCode(float[]a)Returnshashcodeofthecontentsofafloatarray staticinthashCode(int[]a)Returnshashcodeofthecontentsofanintarray. staticinthashCode(long[]a)Returnshashcodeofthecontentsofalongarray staticinthashCode(Object[]a)Returnshashcodeofthecontentsofobjectarray staticinthashCode(short[]a)Returnshashcodeofthecontentsoftheshortarray TheabovetablesshowsallthemethodstheArraysclassprovides.Mostoftheseareoverloadedforvariousprimitivetypes. Let’sdiscusssomeofthesemethodsindetail. #1)asList Prototype:staticListasList(Object[]a) Parameters:a–arrayofobjectsfromwhichthelistwillbebacked. ReturnValue:List=>fixed-sizelistofspecifiedarray Description:Returnsafixed-sizeserializablelistbackedbyanarrayprovidedasanargument. Example: importjava.util.Arrays; importjava.util.List; publicclassMain{ publicstaticvoidmain(String[]args){ String[]months={"January","February","March","April","May"}; //convertedstringarraytoaListusingasList System.out.println("Thestringarrayconvertedtolist:"); List<String>month_list=Arrays.asList(months); System.out.println(month_list); } } Output: Theaboveprogramdemonstratestheusageofthe‘asList’methodofArraysclass.Here,wehavedeclaredastringarrayandpassedittoasListmethodtoobtainalist. #2)binarySearch Prototype:staticintbinarySearch(int[]a,intkey) Parameters: a=>arrayinwhichthekeyistobesearched Key=>elementvaluetobesearched ReturnValue:int=>position(index)atwhichkeyisfound,elsereturns(-(the“insertionpoint”)–1). Description:Searchesforthespecifiedkeyinthegivenarrayusingabinarysearchalgorithm.Thearrayneedstobesortedforthebinarysearchtowork.Ifthearrayisnotsortedthentheresultsareundefined.Also,iftherearemultiplelocationsinthearrayforthesamekeyvalue,thepositionreturnedisnotguaranteed. Example: importjava.util.Arrays; importjava.util.List; publicclassMain{ publicstaticvoidmain(String[]args) { //definetheArray intnumArr[]={23,43,26,65,35,16,74,27,98}; //sortthearrayfirst Arrays.sort(numArr); System.out.println("Inputarray:"+Arrays.toString(numArr)); intkey=35; //callbinarySearchfunctiontosearchagivenkey System.out.println("Key"+key+"foundatindex="+Arrays .binarySearch(numArr,key)); } } Output: Intheaboveprogramfirst,wesorttheinputarraysinceforbinarySearchthearrayshouldbesorted.Thenthearrayandthekeytobesearchedarepassedtothe‘binarySearch’method.Theindexatwhichthekeyisfoundisdisplayedintheoutput. Prototype:staticintbinarySearch(int[]a,intfromIndex,inttoIndex,intkey) Parameters: a=>arraytobesearched fromIndex=>startingindexoftherangeoverwhichthekeyistobesearched toIndex=>theindexofthelastelementintherange key=>keytobesearchedfor ReturnValue:indexofthekeyelementisfoundinthespecifiedrange.Otherwiseitreturns(-(the“insertionpoint”)–1). Description:ThisoverloadofbinarySearchsearchesforakeyvalueinthespecifiedrangeofthearrayandreturnstheindexpositionofthekeyelementiffound.ThearrayandthereforetherangeneedtobesortedforbinarySearchtowork.Ifit’snotsorted,thentheresultsareundefined. Example: importjava.util.Arrays; importjava.util.List; publicclassMain{ publicstaticvoidmain(String[]args) { intnumArr[]={23,43,26,65,35,16,74,27,98};//definetheArray Arrays.sort(numArr);//sortthearrayfirst System.out.println("Inputarray:"+Arrays.toString(numArr)); intkey=35; //callbinarySearchfunctiontosearchagivenkey System.out.println("Key"+key+"foundatindex="+Arrays .binarySearch(numArr,3,7,key)); } } Output: TheaboveprogramisthesameasthepreviousonewithadifferencethatinthecalltobinarySearchmethod,wehavespecifiedarangeofthearrayinwhichthesearchistobeconducted. #3)copyOf Prototype:staticint[]copyOf(int[]original,intnewLength) Parameters: original=>arraytobecopied newLength=>lengthofthecopiedarray ReturnValue:Anewarraycopiedfromtheoriginalandpaddedortruncatedwithzerosdependingonaspecifiedlength. Description:Copiesthearrayoriginalintoanewarrayandpadsortruncatesitwithzerosdependingonthelengthspecified. Example: importjava.util.Arrays; publicclassMain{ publicstaticvoidmain(String[]args) { //definetheArray StringstrArr[]={"Java","Python","Perl","C","Ruby"}; //printtheoriginalarray System.out.println("OriginalStringArray:" +Arrays.toString(strArr)); //copythearrayintonewarrayusingcopyOfandprintit System.out.println("CopiedArray:" +Arrays.toString( Arrays.copyOf(strArr,5))); } } Output: Theaboveprogramdemonstratestheuseofthe‘copyOf’methodofArraysclassthatcopiesthegivenarrayintoanewone.Theaboveprogramcopiestheoriginalstringarrayintoanewarray. #4)copyOfRange Prototype:staticint[]copyOfRange(int[]original,intfrom,intto) Parameters: original=>arrayfromwhichvaluesintherangearetobecopied From=>firstindexoftherange To=>lastindexoftherange ReturnValue:Newarraywithvaluesfromthespecifiedrangewithzerostruncatedorpaddedtoobtainthedesiredlength. Description:Copiestherangespecifiedfromagivenarrayintoanewarray.Thestartedindexofthearrayshouldbeinclusivebetween0tooriginal.length.Theendindexcanbeexclusive. Example: importjava.util.Arrays; publicclassMain{ publicstaticvoidmain(String[]args) { //definetheArray StringstrArr[]={"Java","Python","Perl","C","Ruby"}; //printtheoriginalarray System.out.println("OriginalStringArray:"+Arrays.toString(strArr)); //copythearrayintonewarrayusingcopyOfRangeandprintit System.out.println("CopiedRangeofArray:" +Arrays.toString( Arrays.copyOfRange(strArr,1,3))); } } Output: Wehavemodifiedthepreviousprogramtousethe‘copyOfRange’methodthatcopiesaspecificrangefromthearrayandformsanewarray.Intheaboveprogram,wehavespecifiedtherangelike1,3.Hencetheoutputshowsanewarrayof2elements. #5)Equals Prototype:staticbooleanequals(int[]a,int[]a2) Parameters: a=>firstarraytobetestedforequality A2=>secondarraytobetestedforequality ReturnValue:Returnstrueifbotharraysareequal. Description:Thismethodchecksifboththearraysareequalandreturntheresults.Thetwoarraysaresaidtobeequalifboththearrayshaveanequalnumberofelementsandthecorrespondingelementsinbotharraysareequal. Example: importjava.util.Arrays; publicclassMain{ publicstaticvoidmain(String[]args){ //definetwoarrays,array_Oneandarray_Two int[]array_One={1,3,5,7}; int[]array_Two={1,3,5,7}; //printthearrays System.out.println("array_One="+Arrays.toString(array_One)); System.out.println("array_Two="+Arrays.toString(array_Two)); //useequalsmethodtocheckforequalityofarrays booleanarray_equal=Arrays.equals(array_One,array_Two); //printtheresults if(array_equal){ System.out.println("equalsmethodreturns"+array_equal+ ",hencearraysarray_Oneandarray_Twoareequal\n"); }else{ System.out.println("equalsmethodreturns"+array_equal+ ",hencearraysarray_Oneandarray_Twoarenotequal\n"); } //definetwomorearrays,firstArray&secondArray int[]firstArray={2,4,6,8}; int[]secondArray={1,3,5,7}; //displaythesearrays System.out.println("firstArray="+Arrays.toString(firstArray)); System.out.println("secondArray="+Arrays.toString(secondArray)); //useequalsmethodtocheckequalityofarrays booleantest_array=Arrays.equals(firstArray,secondArray); //printtheresults if(test_array){ System.out.println("equalsmethodreturns"+test_array+ ",hencearraysfirstArrayandsecondArrayareequal\n"); }else{ System.out.println("equalsmethodreturns"+test_array+ ",hencearraysfirstArrayandsecondArrayarenotequal\n"); } } } Output: Theaboveprogramdemonstratesthe‘equals’method.Here,wehaveusedtwosetsofarraysandcalled‘equals’twice.Inthefirstcalltoequals,botharraysarethesameandhencethemethodreturnstrue.Inthesecondcalltoequals,thetwoarraysaredifferentandthemethodreturnsfalse. #6)Fill Prototype:staticvoidfill(int[]a,intval) Parameters: a=>arraytobefilled val=>valuetobefilledinallplacesinarray ReturnValue:None Description:Fillsthearraywiththespecifiedvalue. Example: importjava.util.Arrays; publicclassMain{ publicstaticvoidmain(String[]args){ //definethearray int[]intArray={1,3,5,7}; //printoriginalarray System.out.println("Theoriginalarray:"+Arrays.toString(intArray)); //callfillmethodtofillthearraywithallzeros Arrays.fill(intArray,0); //printalteredarray System.out.println("Arrayaftercalltofill:"+Arrays.toString(intArray)); } } Output: Theaboveprogramshowsthebasicversionofthefillmethod.Here,wejustfilltheentirearraybyanothervalue.Inthiscase,wehavefilledthearraywithallzeros. Prototype:staticvoidfill(int[]a,intfromIndex,inttoIndex,intval) Parameters: a=>arraywhoserangeistobefilled fromIndex=>startindexoftherange toIndex=>endindexoftherange val=>valuewithwhichtheelementsintherangeistobefilled ReturnValue:None Description:FillsthespecifiedrangefromfromIndextotoIndexinthearray‘a’withthespecifiedvalue.IffromIndex=toIndex,thentherangetobefilledisempty. Example: importjava.util.Arrays; publicclassMain{ publicstaticvoidmain(String[]args){ //definethearray int[]intArray={1,3,5,7,9,11,13,15,17}; //printoriginalarray System.out.println("Theoriginalarray:"+Arrays.toString(intArray)); //callfillmethodtofilltherange(2,6)inthearraywithzeros Arrays.fill(intArray,2,6,0); //printalteredarray System.out.println("Arrayaftercalltofilltherange(2,6):"+Arrays.toString(intArray)); } } Output: Thisisanotherversionofthefillmethodwherein,wespecifytheparticularrangeinthearraywhichistobefilledwithadifferentvalue.Intheaboveprogram,wehavespecifiedtherange[2,6]tobefilledwithzeros.Theotherelementsremainthesameasshownintheoutput. #7)Sort Prototype:staticvoidsort(int[]a) Parameters:a=>arraytobesorted ReturnValue:None Description:Thismethodsortsthearrayinascendingorder. Example: importjava.util.Arrays; publicclassMain{ publicstaticvoidmain(String[]args){ //definethearray int[]intArray={10,4,25,63,21,51,73,24,87,18}; //printoriginalarray System.out.println("Theoriginalarray:"+Arrays.toString(intArray)); //callsortmethodtosortthegivenarrayinascendingorder Arrays.sort(intArray); //printalteredarray System.out.println("Sortedarray:"+Arrays.toString(intArray)); } } Output: TheaboveprogramsortsanarrayofintegersusingthesortmethodofArraysclassandprintsthesortedarray. Prototype:staticvoidsort(int[]a,intfromIndex,inttoIndex) Parameters: a=>arrayfromwhicharangeistobesorted fromIndex=>startindexfortherange toIndex=>endindexfortherange ReturnValue:none Description:SortstherangespecifiedfromfromIndextotoIndexinascendingorder.IffromIndex=toIndex,thenrangetobesortedisempty. Example: importjava.util.Arrays; publicclassMain{ publicstaticvoidmain(String[]args){ //definethearray int[]intArray={10,4,25,63,21,51,73,24,87,18}; //printoriginalarray System.out.println("Theoriginalarray:"+Arrays.toString(intArray)); //callsortmethodtosortthegivenrangeinthearrayinascendingorder Arrays.sort(intArray,2,7); //printalteredarray System.out.println("Sortedrange(2,7)inthearray:"+Arrays.toString(intArray)); } } Output: Theaboveprogramdemonstratesthevariationofsortmethod.Inthis,wecanspecifyarangeoverwhichthearrayistobesorted.Theelementsoutofthisrangearenotsorted.Intheaboveprogram,therange[2,7]inthegivenarrayisspecifiedtobesortedinthesortmethod. Henceintheoutput,wecanseethatonlytheelementsinthisrangearesortedinascendingorder. #8)toString Prototype:staticStringtoString(int[]a) Parameters:a=>arraywhosestringrepresentationisrequired ReturnValue:string=>stringrepresentationofarray Description:Convertsthegivenarrayintoitsstringrepresentation. Example: importjava.util.*; publicclassMain { publicstaticvoidmain(String[]args){ //declarearraysoftypeintanddouble int[]intArray={10,20,30,40,50}; double[]dblArray={1.0,2.0,3.0,4.0,5.0}; System.out.println("StringrepresentationofintArray:"); //printstringrepresentationofintarrayusingtoString System.out.println(Arrays.toString(intArray)); System.out.println("\nStringrepresentationofdoubleArray:"); //printstringrepresentationofdoublearrayusingtoString System.out.println(Arrays.toString(dblArray)); } } Output: Intheaboveexample,wehaveusedthetoStringmethodthatconvertsthearraystoastringrepresentation.Sotodemonstratethismethod,wehaveusedtwoarrayseachoftypeintanddouble.ThenusingthetoStringmethod,eachofthisarrayisconvertedtoitscorrespondingstringrepresentationshownintheoutput. #9)hashCode Prototype:staticinthashCode(int[]a) Parameters:a=>arraywhosehashcodeistobecomputed. ReturnValue:int=>hashcodecomputed Description:Themethodreturnsthehashcodeofagivenarray.Thehashcode ofa JavaObjectisactuallya32-bitnumber(signedint).Usinghashcodeyoucanmanageanobjectusinghash-basedstructure. HashcodeisallocatedbyJVMtoanobjectandisusuallyuniqueunlessthetwoobjectsareequaltoeachotherinwhichcaseboththeobjectswillhavethesamehashcode. Example: importjava.util.*; publicclassMain { publicstaticvoidmain(String[]args){ //declarearraysoftypeint int[]intArray={10,20,30,40,50}; //printtheinputarray System.out.println("TheinputArray:"+Arrays.toString(intArray)); //gethashcodeofthearrayusing'hashCode'methodofarray inthashCde=Arrays.hashCode(intArray); //printthehashCode System.out.println("ThehashCodeforinputarray:"+hashCde); } } Output: ThehashCodemethodcomputesthehashcodeforthegivenarraypassedasanargumenttoit. FrequentlyAskedQuestions Q#1)Whatarejava.utilarrays? Answer:Theclassjava.util.Arraysextendfromtheclassjava.lang.Object.TheArraysclasscontainsthemethodtorepresentarraysasalist.Italsocontainsvariousmethodstomanipulatethearrayslikesorting,searching,representingarraysasstrings,etc. Q#2)WhichsortingisusedinarrayssortinJava? Answer:ThesortmethodofArraysclassinJavausestwosortingtechniques.Itusesquicksortwhenprimitivetypesareusedwhereaswhenobjectsareusedthatimplementcomparableinterface,mergesortisused. Q#3)WhatdoesArrays.sort()methoddoinJava? Answer:TheArrays.sort()methodinJavahasvariousoverloadsusingwhichyoucanperformsortingonarrays.Ithasoverloadsforsortingdifferentprimitivedatatype’sarrays. Inaddition,theArrays.sort()methodhasvariousoverloadsforsortinganarrayoveraspecifiedrange.Apartfromthis,theArrays.sort()methodalsoallowsustosortdependingonthecomparatorprovided. Q#4)Whatarecollectionsandarraysclass? Answer:CollectionsaredynamicinnatureandtheclassCollectionsprovidesdirectmethodsthatactoncollections.ArraysarestaticinnatureandhaveclassArraysthatprovidemethodstomanipulatearrays. Butthesearenotdirectmethodsi.e.Arrayobjectscannotinvokethesemethods.Instead,anarrayobjectispassedasanargumenttothesemethods. Conclusion Arraysclassbelongstojava.utilpackageandextendsfromjava.lang.Objectclass.Arraysclasscontainsmethodsthatareusedtomanipulatearrays.Thesemethodsincludethoseusedforsortingarrays,searchingforaparticularelementinarrays,fillingthearraywithaspecificvalue,methodstocomparearrays,etc. Eachofthesemethodshasvariousoverloadsthatallowtheprogrammertoinvokethesemethodsonarraysofdifferentdatatypesandalsoonpartorwholearrays. Inthistutorial,wehavediscussedmostofthemethodsofarraysclass.Wealsosawabriefdescriptionandexamplesofthemajormethods.Theseexamplescanbereplicatedforvariousdatatypesandweleaveityou. =>VisitHereToLearnJavaFromScratch. RecommendedReading JavaArrayLengthTutorialWithCodeExamples JaggedArrayInJava-TutorialWithExamples JAVATutorialForBeginners:100+Hands-onJavaVideoTutorials WhatIsJavaVector|JavaVectorClassTutorialWithExamples HowToSortAnArrayInJava-TutorialWithExamples ReverseAnArrayInJava-3MethodsWithExamples JavaGenericArray-HowToSimulateGenericArraysInJava? JavaCopyArray:HowToCopy/CloneAnArrayInJava AboutSoftwareTestingHelpHelpingourcommunitysince2006! MostpopularportalforSoftwareprofessionalswith240million+visitsand300,000+followers!YouwillabsolutelyloveourcreativecontentonSoftwareToolsandServicesReviews! RecommendedReading JavaArrayLengthTutorialWithCodeExamples JaggedArrayInJava–TutorialWithExamples JAVATutorialForBeginners:100+Hands-onJavaVideoTutorials WhatIsJavaVector|JavaVectorClassTutorialWithExamples HowToSortAnArrayInJava–TutorialWithExamples ReverseAnArrayInJava–3MethodsWithExamples JavaGenericArray–HowToSimulateGenericArraysInJava? JavaCopyArray:HowToCopy/CloneAnArrayInJava JOINOurTeam!



請為這篇文章評分?