Array Copy in Java - GeeksforGeeks
文章推薦指數: 80 %
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
延伸文章資訊
- 1在Java 中複製陣列| D棧 - Delft Stack
javaCopy import java.util.Arrays; public class CopyArray { public static void main(String[] args)...
- 2Java Copy Arrays (Using System arraycopy ... - Programiz
In Java, the System class contains a method named arraycopy() to copy arrays. This method is a be...
- 3Java.lang.System.arraycopy() Method - Tutorialspoint
The java.lang.System.arraycopy() method copies an array from the specified source array, beginnin...
- 4[Java]陣列複製System.arraycopy - 佛祖球球
在Java中,如果陣列單純使用a = b的方式,這樣會變成參照到同一個陣列物件. 如果要複製陣列內容到另一個陣列物件,可以使用System.arraycopy.
- 5java.lang.System.arraycopy()方法實例 - 極客書
java.lang.System.arraycopy() 方法複製從指定源數組的數組,開始在指定的位置, ... public static void arraycopy(Object src,...