System.arraycopy
अधिक प्रदर्शनकारी है लेकिन सूचकांक गणनाओं के कारण सही होने के लिए मुश्किल है। यदि आपके पास प्रदर्शन आवश्यकताओं की आवश्यकता नहीं है तो jrad उत्तर या ArrayList
के साथ बेहतर छड़ी।
public static int[] insert(
int[] array, int elementToInsert, int index) {
int[] result = new int[array.length + 1];
// copies first part of the array from the start up until the index
System.arraycopy(
array /* src */,
0 /* srcPos */,
result /* dest */,
0 /* destPos */,
index /* length */);
// copies second part from the index up until the end shifting by 1 to the right
System.arraycopy(
array /* src */,
index /* srcPos */,
result /* dest */,
index + 1 /* destPos */,
array.length - index /* length */);
result[index] = elementToInsert;
return result;
}
और यह जांचने के लिए JUnit4 परीक्षण अपेक्षित कार्य करता है।
@Test
public void shouldInsertCorrectly() {
Assert.assertArrayEquals(
new int[]{1, 2, 3}, insert(new int[]{1, 3}, 2, 1));
Assert.assertArrayEquals(
new int[]{1}, insert(new int[]{}, 1, 0));
Assert.assertArrayEquals(
new int[]{1, 2, 3}, insert(new int[]{2, 3}, 1, 0));
Assert.assertArrayEquals(
new int[]{1, 2, 3}, insert(new int[]{1, 2}, 3, 2));
}
आप जावा में सरणियों के लिए अनुक्रमित बदलाव नहीं कर सकते हैं । Arrays निश्चित आकार हैं। अपने इच्छित मानों के साथ नई सरणी बनाएं और संदर्भ 'ए' को नई सरणी में असाइन करें। – kosa
गृहकार्य? यदि ऐसा है, तो इसे इस तरह टैग करें। –
अब बहुत देर हो चुकी है क्योंकि पहले से ही एक पूर्ण-कोड उत्तर है। –