patternjavaMinor
Insert k copies of each element in ArrayList
Viewed 0 times
inserteachcopieselementarraylist
Problem
This method takes an
ArrayList s and int k , then creates k copies of each element.public static void copyStrings(ArrayList s, int k) {
if (k <= 0) {
s.clear();
} else {
int limit = s.size();
for(int i = 0; i < limit; i++) {
for( int j = 0; j < k; j++) {
s.add(s.get(i));
}
}
for( int i = 0; i < limit; i++) {
s.remove(0);
}
}
}Solution
You have double the indenting that you should inside your method.
Rather than calling
I'd recommend renaming
Why are you making it specific to
Aside from that, there's not much. Your code is pretty short, and there isn't much to say. Here's your code with these tips applied:
Rather than calling
s.get(i) every time, store it in a variable and use from that instead. Incidentally, this means that you can use an advanced for instead of a simple one.I'd recommend renaming
limit to originalSize, so that it's clear what it is.s isn't descriptive. Why not call it source? Ditto with k -- why not call it copies?Why are you making it specific to
Strings, when it's almost just a find-and-replace away from being a generic method? If you make it generic, it'll work with any type, not just the one.Aside from that, there's not much. Your code is pretty short, and there isn't much to say. Here's your code with these tips applied:
public static void copyStrings(ArrayList source, int copies) {
if (copies <= 0) {
source.clear();
} else {
int limit = source.size();
for(E element : source) {
for( int j = 0; j < copies; j++) {
source.add(element);
}
}
for( int i = 0; i < limit; i++) {
source.remove(0);
}
}
}Code Snippets
public static <E> void copyStrings(ArrayList<E> source, int copies) {
if (copies <= 0) {
source.clear();
} else {
int limit = source.size();
for(E element : source) {
for( int j = 0; j < copies; j++) {
source.add(element);
}
}
for( int i = 0; i < limit; i++) {
source.remove(0);
}
}
}Context
StackExchange Code Review Q#95169, answer score: 7
Revisions (0)
No revisions yet.