Answer:
package lab1;
import java.util.ArrayList;
import java.util.Iterator;
public class ArrayListMethodsTester
{
public static void main(String[] args)
{
ArrayList<String> stringArray = new ArrayList<String>();
stringArray.add("This");
stringArray.add("is");
stringArray.add("an");
stringArray.add("ArrayList");
stringArray.add("of");
stringArray.add("Strings");
System.out.println("Printing the arraylist:");
ArrayListMethods.print(stringArray);
System.out.println("\nArrayList is condensing:");
ArrayListMethods.condense(stringArray);
ArrayListMethods.print(stringArray);
System.out.println("\nArrayList is duplicating:");
ArrayListMethods.duplicate(stringArray);
ArrayListMethods.print(stringArray);
}
}
class ArrayListMethods
{
static void print(ArrayList stringArray)
{
Iterator it = stringArray.iterator();
while (it.hasNext())
System.out.println(it.next() + " ");
}
static void condense(ArrayList stringArray)
{
int length=stringArray.size();
ArrayList cloneArray=(ArrayList) stringArray.clone();
stringArray.clear();
StringBuilder sb=new StringBuilder("");
for (int i = 0; i < (length/2); i++)
{
sb.append(cloneArray.get(i));
sb.append(" ");
}
stringArray.add(sb);
StringBuilder sb1=new StringBuilder("");
for (int i = (length/2); i < length; i++)
{
sb1.append(cloneArray.get(i));
sb1.append(" ");
}
stringArray.add(sb1);
}
static void duplicate(ArrayList stringArray)
{
for (int i = 0; i < stringArray.size(); i+=2)
{
stringArray.add(i+1,stringArray.get(i));
}
}
}
Explanation:
- Get the length of the arraylist to copy the array into another arraylist
.
- Empty the array so that new content can be stored in it
.
- Use a loop to half of array_list.
- Use a loop from half of array_list to the end of arraylist and append all into a single string.