Array Copy in Java - GeeksforGeeks

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

clone() creates a new array of the same size, but System.arraycopy() can be used to copy from a source range to a destination range. System. Skiptocontent CoursesForWorkingProfessionalsLIVEDSALiveClassesSystemDesignJavaBackendDevelopmentFullStackLIVEExploreMoreSelf-PacedDSA-SelfPacedSDETheoryAllDevelopmentCoursesExploreMoreForStudentsLIVECompetitiveProgrammingGATELiveCourse2023DataScienceExploreMoreSelf-PacedDSA-SelfPacedCIPJAVA/Python/C++ExploreMoreSchoolCoursesSchoolGuidePythonProgrammingLearnToMakeAppsExploremoreAllCoursesTutorialsAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#HTMLJavaScriptPHPSQLScalaPerlGoLanguageKotlinML&DataScienceMachineLearningDataScienceCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebDevelopmentHTMLCSSJavaScriptPHPCSSFrameworksBootstrapTailwindCSSFoundationCSSMaterializeCSSBulmaPureCSSPrimerCSSBlazeUISemanticUIJavaScriptFrameworksAngularJSNodeJSJavaScriptLibrariesjQueryReactJSSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialGFGSheetsWebDevCheatSheetsHTMLCheatSheetCSSCheatSheetJSCheatSheetjQueryCheatSheetCompany-WiseSDESheetsFacebookSDESheetAmazonSDESheetAppleSDESheetNetflixSDESheetGoogleSDESheetWiproCodingSheetInfosysCodingSheetTCSCodingSheetCognizantCodingSheetHCLCodingSheetDSASheetsSDESheetFAANGCodingSheetLoveBabbarSheetMassRecruiterSheetProduct-BasedCodingSheetCompany-WisePreparationSheetArraySheetStringSheetTreeSheetGraphSheetDPSheetSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesChemistryNotesClass8NotesClass9NotesClass10NotesCSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsStudentChapterGeekontheTopInternshipCareersJobsApplyforJobsPostaJobHirewithUsKnowaboutJobathonJobathonPracticeAllDSAProblemsProblemoftheDayInterviewSeries:WeeklyContestsBi-WizardCoding:SchoolContestsContestsandEventsPracticeSDESheetCuratedDSAListsTop50ArrayProblemsTop50StringProblemsTop50TreeProblemsTop50GraphProblemsTop50DPProblemsContests ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantriHomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningJavaScriptSDESheetPuzzlesGFGSchoolProjects RelatedArticles ▲RelatedArticlesBasicsJavaProgrammingLanguageIntroductiontoJavaSettinguptheenvironmentinJavaJavaBasicSyntaxJavaHelloWorldProgramCommandLineArgumentsinJavaHowJVMWorks–JVMArchitecture?DifferencesbetweenJDK,JREandJVMJavaIdentifiersDatatypesinJavaVariablesinJavaCommentsinJavaOperatorsinJavaWaystoreadinputfromconsoleinJavaFlowControlDecisionMakinginJava(if,if-else,switch,break,continue,jump)LoopsinJavaJavaForloopwithExamplesFor-eachloopinJavaJavawhileloopwithExamplesSwitchStatementinJavaContinueStatementinJavaBreakstatementinJavaStringsStringsinJavaStringclassinJava|Set1StringBufferclassinJavaStringBuilderClassinJavawithExamplesArraysArraysinJavaMultidimensionalArraysinJavaJaggedArrayinJavaArrayCopyinJavaHowtoconvertanArraytoStringinJava?CompareTwoArraysinJavaMethodsMethodsinJavaParameterPassingTechniquesinJavawithExamplesReturningMultiplevaluesinJavaDifferentwaysofMethodOverloadinginJavaScopeofVariablesInJavaConstructorsConstructorsinJavaCopyConstructorinJavaConstructorOverloadinginJavaConstructorChainingInJavawithExamplesPrivateConstructorsandSingletonClassesinJavaOOPConceptsClassesandObjectsinJavaInheritanceinJavaEncapsulationinJavaPolymorphisminJavaAbstractioninJavaOverridinginJavaMethodOverloadinginJavaExceptionHandlingExceptionsinJavaTypesofExceptioninJavawithExamplesCheckedvsUncheckedExceptionsinJavathrowandthrowsinJavaUser-definedCustomExceptioninJavaInterfaces&AbstractClassesInterfacesinJavaNestedInterfaceinJavaMarkerinterfaceinJavaAbstractClassinJavaDifferencebetweenAbstractClassandInterfaceinJavaFunctionalInterfacesinJavaComparatorInterfaceinJavawithExamplesCollectionsCollectionsinJavaCollectionsClassinJavaCollectionvsCollectionsinJavawithExampleJava|ImplementingIteratorandIterableInterfaceListInterfaceinJavawithExamplesArrayListinJavaVectorClassinJavaStackClassinJavaLinkedListinJavaQueueInterfaceInJavaPriorityQueueinJavaDequeinterfaceinJavawithExampleArrayDequeinJavaSetinJavaHashSetinJavaLinkedHashSetinJavawithExamplesSortedSetInterfaceinJavawithExamplesNavigableSetinJavawithExamplesTreeSetinJavaMapInterfaceinJavaHashMapinJavawithExamplesHashtableinJavaLinkedHashMapinJavaSortedMapInterfaceinJavawithExamplesTreeMapinJavaMultithreadingMultithreadinginJavaLifecycleandStatesofaThreadinJavaMainthreadinJavaJavaThreadPriorityinMultithreadingSynchronizationinJavaFileHandlingFileHandlinginJavawithCRUDoperationsJava.io.InputStreamClassinJavaJava.io.OutputStreamclassinJavaJava.io.FileClassinJavaFilePermissionsinJavaCopyingfileusingFileStreamsinJavaDeleteaFileUsingJavaBasicsJavaProgrammingLanguageIntroductiontoJavaSettinguptheenvironmentinJavaJavaBasicSyntaxJavaHelloWorldProgramCommandLineArgumentsinJavaHowJVMWorks–JVMArchitecture?DifferencesbetweenJDK,JREandJVMJavaIdentifiersDatatypesinJavaVariablesinJavaCommentsinJavaOperatorsinJavaWaystoreadinputfromconsoleinJavaFlowControlDecisionMakinginJava(if,if-else,switch,break,continue,jump)LoopsinJavaJavaForloopwithExamplesFor-eachloopinJavaJavawhileloopwithExamplesSwitchStatementinJavaContinueStatementinJavaBreakstatementinJavaStringsStringsinJavaStringclassinJava|Set1StringBufferclassinJavaStringBuilderClassinJavawithExamplesArraysArraysinJavaMultidimensionalArraysinJavaJaggedArrayinJavaArrayCopyinJavaHowtoconvertanArraytoStringinJava?CompareTwoArraysinJavaMethodsMethodsinJavaParameterPassingTechniquesinJavawithExamplesReturningMultiplevaluesinJavaDifferentwaysofMethodOverloadinginJavaScopeofVariablesInJavaConstructorsConstructorsinJavaCopyConstructorinJavaConstructorOverloadinginJavaConstructorChainingInJavawithExamplesPrivateConstructorsandSingletonClassesinJavaOOPConceptsClassesandObjectsinJavaInheritanceinJavaEncapsulationinJavaPolymorphisminJavaAbstractioninJavaOverridinginJavaMethodOverloadinginJavaExceptionHandlingExceptionsinJavaTypesofExceptioninJavawithExamplesCheckedvsUncheckedExceptionsinJavathrowandthrowsinJavaUser-definedCustomExceptioninJavaInterfaces&AbstractClassesInterfacesinJavaNestedInterfaceinJavaMarkerinterfaceinJavaAbstractClassinJavaDifferencebetweenAbstractClassandInterfaceinJavaFunctionalInterfacesinJavaComparatorInterfaceinJavawithExamplesCollectionsCollectionsinJavaCollectionsClassinJavaCollectionvsCollectionsinJavawithExampleJava|ImplementingIteratorandIterableInterfaceListInterfaceinJavawithExamplesArrayListinJavaVectorClassinJavaStackClassinJavaLinkedListinJavaQueueInterfaceInJavaPriorityQueueinJavaDequeinterfaceinJavawithExampleArrayDequeinJavaSetinJavaHashSetinJavaLinkedHashSetinJavawithExamplesSortedSetInterfaceinJavawithExamplesNavigableSetinJavawithExamplesTreeSetinJavaMapInterfaceinJavaHashMapinJavawithExamplesHashtableinJavaLinkedHashMapinJavaSortedMapInterfaceinJavawithExamplesTreeMapinJavaMultithreadingMultithreadinginJavaLifecycleandStatesofaThreadinJavaMainthreadinJavaJavaThreadPriorityinMultithreadingSynchronizationinJavaFileHandlingFileHandlinginJavawithCRUDoperationsJava.io.InputStreamClassinJavaJava.io.OutputStreamclassinJavaJava.io.FileClassinJavaFilePermissionsinJavaCopyingfileusingFileStreamsinJavaDeleteaFileUsingJavaArrayCopyinJavaViewDiscussion ImproveArticle SaveArticle LikeArticle DifficultyLevel: EasyLastUpdated: 26Oct,2021ReadDiscussViewDiscussion ImproveArticle SaveArticle LikeArticle Givenanarray,weneedtocopyitselementsinadifferentarray,toanaiveuserbelowwaycomesintomindwhichishoweverincorrectasdepictedbelowasfollows://JavaProgramtoIllustrateWrongWayOfCopyinganArray //Inputarray inta[]={1,8,3}; //Creatinganarrayb[]ofsamesizeasa[] intb[]=newint[a.length]; //Doesn'tcopyelementsofa[]tob[],onlymakes //brefertosamelocation b=a;Output: OutputExplanation:Whenwedo“b=a”,weareactuallyassigningareferencetothearray.Hence,ifwemakeanychangetoonearray,itwouldbereflectedinotherarraysaswellbecausebothaandbrefertothesamelocation.Wecanalsoverifyitwithcodeasshownbelowasfollows:Example:Java//AJavaprogramtodemonstratethatsimply//assigningonearrayreferenceisincorrectpublicclassTest{    publicstaticvoidmain(String[]args)    {        inta[]={1,8,3};         //Createanarrayb[]ofsamesizeasa[]        intb[]=newint[a.length];         //Doesn'tcopyelementsofa[]tob[],        //onlymakesbrefertosamelocation        b=a;         //Changetob[]willalsoreflectina[]        //as'a'and'b'refertosamelocation.        b[0]++;         System.out.println("Contentsofa[]");        for(inti=0;i



請為這篇文章評分?