Java arrays
Engineer 20 Apr 2013
This intended for the experienced Java programmer, I want to show my Java code that manipulates arrays and I gladly want to improve it. However, one thing: I know its better to use arraylists, but this is just some practise for my Java programming skills.
Well here is my "array-util" code:
You could say I have no experience in Java programming, so thats why I made this.
I would love some feedback on how to improve things, or even feedback to let me know this is good
Thank you in advance,
- Engineer
Well here is my "array-util" code:
public String[] removeFrom(String[] array, int index) { String[] newArray = new String[array.length - 1]; int newIndex = 0; for(int i = 0; i < array.length; i++) { if(i != index) { newArray[newIndex] = array[i]; newIndex++; } } array = null; return newArray; } //Set index to -1 to add it at the end public String[] addItem(String[] array, String item, int index) { String[] newArray = new String[array.length + 1]; int realIndex = 0; for(int i = 0; i < array.length; i++) { if(i == index) { newArray[i] = null; } else { newArray[i] = array[realIndex]; realIndex++; } } if(index == -1) { newArray[array.length + 1] = item; } else { newArray[index] = item; } array = null; return newArray; } public String[] replaceIndex(String[] array, int index, String newString) { String[] newArray = new String[array.length]; for(int i = 0; i < array.length; i++) { if(i == index) { newArray[i] = newString; } else { newArray[i] = array[i]; } } array = null; return newArray; }
You could say I have no experience in Java programming, so thats why I made this.
I would love some feedback on how to improve things, or even feedback to let me know this is good
Thank you in advance,
- Engineer
Mads 20 Apr 2013
Nice. But you could use templates(or whatever they're called in Java), so that it doesn't care about type. And you could create something like a class Container<T>, which would then do all of the stuff to member variables.(hard to explain, I'm tired as shit)
ElvishJerricco 20 Apr 2013
A lot of you code could be vastly simplified by using System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
Engineer 20 Apr 2013
Mads, on 20 April 2013 - 10:14 AM, said:
Nice. But you could use templates(or whatever they're called in Java), so that it doesn't care about type. And you could create something like a class Container<T>, which would then do all of the stuff to member variables.(hard to explain, I'm tired as shit)
ElvishJerricco, on 20 April 2013 - 10:51 AM, said:
A lot of you code could be vastly simplified by using System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
ElvishJerricco 21 Apr 2013
EDIT: Sorry i wanted to post a lot but the formatting was tripping out because HTML and <> in my [CODE] tags didn't get along